package com.platform.qujia.service.impl;

import com.platform.qujia.constantEnum.Constant;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.dao.*;
import com.platform.qujia.enums.ElectronCardType;
import com.platform.qujia.param.request.AddPayOrderParam;
import com.platform.qujia.enums.PayTypeEnum;
import com.platform.qujia.param.request.PayOrderRequest;
import com.platform.qujia.param.response.reductionResponse;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.ReductionAndCouponDTO;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.LocalDateTimeUtil;
import com.platform.qujia.utils.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 立减活动Service业务层处理
 *
 * @author qujia
 * @date 2021-11-03
 */
@Service("reductionActivityService")
@Slf4j
public class ReductionActivityServiceImpl implements ReductionActivityService
{
    @Resource
    private ReductionActivityMapper reductionActivityMapper;
    @Resource
    private ReductionRulesMapper reductionRulesMapper;
    @Resource
    private ReductionActivityLogMapper reductionActivityLogMapper;
    @Resource
    private ReductionOilRelationsMapper reductionOilRelationsMapper;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private GradeMapper gradeMapper;
    @Resource
    private AppUserSuperDetailMapper appUserSuperDetailMapper;
    @Resource
    private AppUserSuperMapper appUserSuperMapper;
    @Resource
    private LabelMapper labelMapper;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private ReductionStationRelationsMapper reductionStationRelationsMapper;

    @Resource
    private ReductionActivityBalanceRecordService reductionActivityBalanceRecordService;
    @Resource
    private ReductionRulesService reductionRulesService;

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private PayOrderHistoryMapper payOrderHistoryMapper;
    @Autowired
    private PhysicalCardMapper physicalCardMapper;

    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private IUserVirtualGradeRelService userVirtualGradeRelService;



    public static final String OLD_ACTIVITY_CREATE_TIME_STR = "2023-08-05 00:00:00";
    public static final LocalDateTime OLD_ACTIVITY_CREATE_TIME = LocalDateTime.of(2023,8,5,0,0,0);

    public static final Map<String,String> MEMBER_LEVEL_MAP = new HashMap<>();

    static {
        MEMBER_LEVEL_MAP.put("月卡","96");
        MEMBER_LEVEL_MAP.put("季卡","97");
        MEMBER_LEVEL_MAP.put("年卡","98");
    }

    @Override
    public Map<String,Object> selectReductionByPayOrder(AppUserInfo appUserInfos, PayOrder payOrder, String activityUse,
                                                        PayOrderRequest payOrderRequest,Station stationInfos, StaOilGun staOilGun) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmt = new SimpleDateFormat("yyyy-MM-dd");

        try{
            log.info("appUserInfos======{}",appUserInfos);
            log.info("payOrder========{}",payOrder);
            log.info("payOrderRequest========{}",payOrderRequest);
            log.info("activityUse========{}",activityUse);

            String payMode = payOrderRequest.getPayType();
            String labelId = payOrderRequest.getLabelId();

            Integer stationId = payOrder.getStationId();//油站id
            //查询用户等级
            String userGrade = "0";
            UserVirtualGradeRel virtualGradeRel = userVirtualGradeRelService.queryUserVirtualGrade(Long.valueOf(payOrder.getEnterpriseId()),
                    Long.valueOf(appUserInfos.getUserId()),LocalDateTime.now());
            if (virtualGradeRel != null) {
                userGrade = virtualGradeRel.getGradeCode();
            }else{
                Grade grade = new Grade();
                grade.setGradeGrowValue(appUserInfos.getGrowUpValue());
                grade.setEnterpriseId(Long.valueOf(appUserInfos.getStationId()));
                grade.setDeleteFlag("0");
                List<Grade> grades = gradeMapper.selectUserGrade(grade);
                log.info("grades===={}",grades);
                if(grades != null && grades.size() == 1){
                    if(grades.get(0).getGradeCode() != null) userGrade = grades.get(0).getGradeCode();
                }
            }
            appUserInfos.setMemberLevel(userGrade);
            // 判断是不是超级会员
            Date now = new Date();
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                    .enterpriseId(Long.valueOf(appUserInfos.getStationId()))
                    .userId(Long.valueOf(appUserInfos.getUserId()))
                    .beginDate(now)
                    .endDate(now)
                    .build());
            if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
                //有记录，是超级会员
                AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(appUserSuperDetails.get(0).getSuperId());
                if (appUserSuper != null) {
                    appUserInfos.setSuperUser(MEMBER_LEVEL_MAP.get(appUserSuper.getSuperName()));
                }
                //appUserInfos.setSuperUser(Constant.MEMBER_LEVEL_SUPER);
            }else{
                // 不是
                appUserInfos.setSuperUser(null);
            }

            //查询用户有没有支付过，支付过就是老用户，没有就是新用户
            appUserInfos.setStaJiBie("1");
            //优化     取消新老用户判断
//            List<PayOrder> userOrderListByUnionId = payOrderMapper.getUserOrderListByUnionId(appUserInfos);
//            String memberTags = "newUser";
//            if(userOrderListByUnionId != null && userOrderListByUnionId.size()>0)memberTags = "oldUser";
//            String memberTags = null;//  优化    暂时填写字段
            String memberCategory = Constant.MEMBER_CATEGORY_OLD_USER;
            Integer userOrderId = getUserOrderId(appUserInfos);
            if (userOrderId == null) {
                memberCategory = Constant.MEMBER_CATEGORY_NEW_USER;
            }
            String oilId = payOrder.getOilName();
//            oilId = "3";//TODO delete
            //计算优惠
            //  BigDecimal orderLiters = new BigDecimal(payOrder.getOrderLiters());//加油升数
            List<ReductionActivity> labreductionActivities = new ArrayList<ReductionActivity>();
            List<ReductionActivity> reductionActivities = new ArrayList<ReductionActivity>();
            //判断用户标签
            Map<String,Object> labelParams = new HashMap<String,Object>();
            log.info("labelId====={}",labelId);
            if(StringUtils.isNotEmpty(labelId)){
                //根据标签id判断标签和关联的活动，判断标签是否是当前油企的
                LabelRule labelRule = new LabelRule();
                labelRule.setLabelId(Integer.valueOf(labelId));
                labelRule.setDelFlag("0");
                labelRule.setEnterpriseId(appUserInfos.getStationId());
                List<LabelRule> labelRuleList = labelMapper.getLabelRuleList(labelRule);
                log.info("labelRuleList=========={}",labelRuleList);
                if(labelRuleList != null && labelRuleList.size() == 1){
                    LabelRule label = labelRuleList.get(0);
                    if(StringUtils.isNotEmpty(label.getActivityIds())){
                        labelParams.put("activityIds",label.getActivityIds());
                        labelParams.put("stationId",stationId);
                        labelParams.put("oilId",oilId);
                        labelParams.put("activityUse","LABEl");
                        labelParams.put("memberLevel",userGrade);
                        labelParams.put("superUser",appUserInfos.getSuperUser());
                        labelParams.put("currentDate",fmt.format(now));
                        labelParams.put("paymentMethod",payMode);
                        labelParams.put("memberCategory",memberCategory);
                        List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
                        log.info("labelReductionActivities================{}",labelReductionActivities);
                        if(labelReductionActivities != null && labelReductionActivities.size() == 1){
                            labreductionActivities.add(labelReductionActivities.get(0));
                        }
                    }
                    if(label.getIsAddLabel().equals("1")){
                        //强制添加的标签，判断用户有没有标签，有就更新标签id 没有就新增标签
                        CustomerLabel customerLabel = new CustomerLabel();
                        customerLabel.setPhone(appUserInfos.getMobilePhone());
                        customerLabel.setEnterpriseId(appUserInfos.getStationId());
                        CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                        log.info("userLabel=============={}",userLabel);
                        if(userLabel != null){
                            //修改标签
                            userLabel.setLabelId(labelId);
                            labelMapper.updateCustomerLabel(userLabel);
                        }
                        else{
                            //新增标签
                            userLabel = new CustomerLabel();
                            userLabel.setLabelId(labelId);
                            userLabel.setDelFlag("0");
                            userLabel.setEnterpriseId(appUserInfos.getStationId());
                            userLabel.setPhone(appUserInfos.getMobilePhone());
                            userLabel.setCreateBy(String.valueOf(appUserInfos.getUserId()));
                            userLabel.setCreateTime(now);
                            userLabel.setUpdateBy(String.valueOf(appUserInfos.getUserId()));
                            userLabel.setUpdateTime(now);
                            userLabel.setStationId(stationId);
                            labelMapper.insertCustomerLabel(userLabel);
                        }
                    }
                }
                else{
                    //根据传入labelId没有查询到有效的标签，根据用户和油企查询是否有标签
                    log.info("11111111111111");
                    CustomerLabel customerLabel = new CustomerLabel();
                    customerLabel.setPhone(appUserInfos.getMobilePhone());
                    customerLabel.setEnterpriseId(appUserInfos.getStationId());
                    CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                    log.info("userLabel============={}",userLabel);
                    if(userLabel != null){
                        labelRule = new LabelRule();
                        labelRule.setLabelId(Integer.valueOf(userLabel.getLabelId()));
                        labelRule.setDelFlag("0");
                        labelRule.setEnterpriseId(appUserInfos.getStationId());
                        //   优化   这个的接口的关联表没有用
                        labelRuleList = labelMapper.getLabelRuleList(labelRule);
                        if(labelRuleList != null && labelRuleList.size() == 1){
                            LabelRule label = labelRuleList.get(0);
                            if(StringUtils.isNotEmpty(label.getActivityIds())){
                                labelParams.put("activityIds",label.getActivityIds());
                                labelParams.put("stationId",stationId);
                                labelParams.put("oilId",oilId);
                                labelParams.put("activityUse","LABEl");
                                labelParams.put("memberLevel",userGrade);
                                labelParams.put("superUser",appUserInfos.getSuperUser());
                                labelParams.put("currentDate",fmt.format(now));
                                labelParams.put("paymentMethod",payMode);
                                labelParams.put("memberCategory",memberCategory);
                                List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
                                log.info("labelReductionActivities========{}",labelReductionActivities);
                                if(labelReductionActivities != null && labelReductionActivities.size() == 1){
                                    labreductionActivities.add(labelReductionActivities.get(0));
                                }
                            }
                        }
                    }
                }
            }
            else{
                log.info("22222222222222222");
                //没有传入标签id，根据用户和油企查询是否有标签
                //根据传入labelId没有查询到有效的标签，根据用户和油企查询是否有标签
                CustomerLabel customerLabel = new CustomerLabel();
                customerLabel.setPhone(appUserInfos.getMobilePhone());
                customerLabel.setEnterpriseId(appUserInfos.getStationId());
                CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);

                if(userLabel != null){
                    LabelRule labelRule = new LabelRule();
                    labelRule.setLabelId(Integer.valueOf(userLabel.getLabelId()));
                    labelRule.setDelFlag("0");
                    labelRule.setEnterpriseId(appUserInfos.getStationId());
                    List<LabelRule> labelRuleList = labelMapper.getLabelRuleList(labelRule);
                    if(labelRuleList != null && labelRuleList.size() == 1){
                        LabelRule label = labelRuleList.get(0);
                        if(StringUtils.isNotEmpty(label.getActivityIds())){
                            labelParams.put("activityIds",label.getActivityIds());
                            labelParams.put("stationId",stationId);
                            labelParams.put("oilId",oilId);
                            labelParams.put("activityUse","LABEl");
                            labelParams.put("memberLevel",userGrade);
                            labelParams.put("superUser",appUserInfos.getSuperUser());
                            labelParams.put("currentDate",fmt.format(now));
                            labelParams.put("paymentMethod",payMode);
                            labelParams.put("memberCategory",memberCategory);
                            List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
                            if(labelReductionActivities != null && labelReductionActivities.size() == 1){
                                labreductionActivities.add(labelReductionActivities.get(0));
                            }
                        }
                    }
                }
            }
            Map<String,Object> queryMap = new HashMap<String,Object>();
            for (ReductionActivity reductionActivity : labreductionActivities) {
                queryMap.clear();
                queryMap.put("userId",appUserInfos.getUserId());
                queryMap.put("reductionActivityId",reductionActivity.getActivityId());
                queryMap.put("startDate",simFmt.format(now)+" 00:00:00");
                queryMap.put("endDate",simFmt.format(now)+" 23:59:59");
                Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
                if(reductionActivity.getMaxCount() != 0){
                    Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
                    if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                        //超出单次活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getAntiCheating().equals("0")){
                    Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
                    //开启了每日次数限制
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                else{
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getActivityMode().equals("RDD")){
                    if(reductionActivity.getBudget() <= 0){
                        //预算不足
                        continue;
                    }
                }
                reductionActivities.add(reductionActivity);
            }
            Double amt = payOrder.getAmt();//实收金额
            queryMap.clear();
            queryMap.put("stationId",stationId);
            queryMap.put("oilId",oilId);
            queryMap.put("activityUse","CSP");
            queryMap.put("memberLevel",userGrade);
            queryMap.put("superUser",appUserInfos.getSuperUser());
            //queryMap.put("memberTags",memberTags);
            queryMap.put("paymentMethod",payMode);
            queryMap.put("currentDate",fmt.format(now));
            queryMap.put("enterpriseId",appUserInfos.getStationId());
            queryMap.put("memberCategory",memberCategory);
            //优化     确定用户不是标签用户

            Calendar calendar = Calendar.getInstance();
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            int month = calendar.get(Calendar.DAY_OF_MONTH);
            if(week == 1){
                week = 7;
            }else{
                week--;
            }
            if(reductionActivities.size() == 0){
                //优化   超级会员的立减活动
//                AppUserSuperDetail appUserSuperDetail = null;
//                List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
//                        .enterpriseId(Long.valueOf(appUserInfos.getStationId().toString()))
//                        .userId(Long.valueOf(appUserInfos.getUserId().toString())).beginDate(new Date()).endDate(new Date()).build());
//                if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
//                    appUserSuperDetail = appUserSuperDetails.get(0);
//                    Long superId = appUserSuperDetail.getSuperId();
//                    AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(superId);
//                    if(appUserSuper != null && appUserSuper.getActivityId() != null){
//                        labelParams.put("activityId",appUserSuper.getActivityId());
//                        labelParams.put("stationId",stationId);
//                        labelParams.put("oilId",oilId);
//                        labelParams.put("activityUse","CSP");
//                        labelParams.put("currentDate",fmt.format(new Date()));
//                        labelParams.put("cardFlag",payOrderRequest.getCardFlag());
//                        List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
//                        if(labelReductionActivities != null && labelReductionActivities.size() == 1){
//                            reductionActivities.add(labelReductionActivities.get(0));
//                        }
//                    }
//                }

                //计算当前是周几以及几号，查询时间是否符合
                queryMap.put("cardFlag",payOrderRequest.getCardFlag());
                queryMap.put("week",week);
                queryMap.put("month",month);
                reductionActivities.addAll(queryOldActivityByDayAndWeek(queryMap));
            }

            ReductionRules reductionRules = null;
            ReductionOilRelations reductionOilRelations = null;
            List<ReductionRules> reductionRuleList = new ArrayList<ReductionRules>();
            ReductionActivity finishReductionActivity = null;
            BigDecimal reductionAmount = BigDecimal.ZERO;
            Double compareNum = 0D;
            reductionActivities=checkLabelUser(reductionActivities,appUserInfos.getMobilePhone(),appUserInfos.getStationId().longValue());
            LocalTime nowTime = LocalTime.now();
            String oilCardType = staOilGun.getOil().getCardType();
            if (Boolean.TRUE.equals(payOrderRequest.getGenericPay())) {
                oilCardType = ElectronCardType.GENERIC.getKey();
            }
            ReductionRules fRules = null;
            for (ReductionActivity reductionActivity : reductionActivities) {

                // 判断支付方式
                if (!checkActivityPayMethod(reductionActivity, payMode,oilCardType,null,null)) {
                    continue;
                }

                //判断金额是否超过活动上限
                if(isAmtUpperLimit(reductionActivity,BigDecimal.valueOf(payOrder.getAmt()))){
                    continue;
                }
                // 判断时间
                if (!checkDayTime(reductionActivity,week,month,nowTime)) {
                    continue;
                }


                reductionRules = new ReductionRules();
                // 查询该活动的限制
                queryMap.clear();
                queryMap.put("userId",appUserInfos.getUserId());
                queryMap.put("reductionActivityId",reductionActivity.getActivityId());
                queryMap.put("startDate",simFmt.format(now)+" 00:00:00");
                queryMap.put("endDate",simFmt.format(now)+" 23:59:59");
                Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
                if(reductionActivity.getMaxCount() != 0){
                    Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
                    if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                        //超出单次活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getAntiCheating().equals("0")){
                    Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
                    //开启了每日次数限制
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }else{
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getActivityType().equals("RFA")){
                    compareNum = amt;
                }else if(reductionActivity.getActivityType().equals("LOR")){
                    compareNum = Double.valueOf(payOrder.getOrderLiters());
                }else if(reductionActivity.getActivityType().equals("AAL")){
                    //按照订单金额及升数
                    compareNum = amt;
                }else if(reductionActivity.getActivityType().equals(Constant.REDUCTION_ACTIVITY_TYPE_LITRE_BY_LITRE)){
                    // 每升立减-按升数
                    compareNum = Double.valueOf(payOrder.getOrderLiters());
                }
                //System.out.println(reductionActivity.getActivityName());
                Long oilPartOrAll = reductionActivity.getOilPartOrAll();
                if(oilPartOrAll == 1){
                    //针对全部油品，规则直接关联活动
                    reductionRules.setActivityId(reductionActivity.getActivityId());
                    reductionRuleList = reductionRulesMapper.selectReductionRulesList(reductionRules);
                }else{
                    //针对部分油品，规则关联油品
                    reductionOilRelations = new ReductionOilRelations();
                    reductionOilRelations.setActivityId(reductionActivity.getActivityId());
                    reductionOilRelations.setOilId(Long.valueOf(oilId));
                    List<ReductionOilRelations> reductionOilRelationsList = reductionOilRelationsMapper.selectReductionOilRelationsList(reductionOilRelations);
                    if(reductionOilRelationsList != null && reductionOilRelationsList.size() == 1){
                        reductionOilRelations = reductionOilRelationsList.get(0);
                        reductionRules.setActivityOilId(reductionOilRelations.getActivityOilId());
                        reductionRuleList = reductionRulesMapper.selectReductionRulesList(reductionRules);
                    }
                }
                //判断立减类型
                if(Constant.REDUCTION_ACTIVITY_MODE_FIXED.equals(reductionActivity.getActivityMode())){
                    //定额立减

                    for (ReductionRules rules : reductionRuleList) {
                        Double full = rules.getFull();
                        BigDecimal dis;
                        //每升立减逻辑
                        if(Constant.REDUCTION_ACTIVITY_TYPE_LITRE.equals(reductionActivity.getActivityType())
                                || Constant.REDUCTION_ACTIVITY_TYPE_LITRE_BY_LITRE.equals(reductionActivity.getActivityType())){
                            // 旧活动的full为空，需要判断一下
                            if(full == null || full <= compareNum){
                                dis = BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2, RoundingMode.HALF_UP);
                            }else{
                                dis = BigDecimal.ZERO;
                            }
                        }else if(full != null && full <= compareNum){
                            // 其它活动类型逻辑
                            dis = BigDecimal.valueOf(rules.getCut());
                        }else{
                            //既不是每升立减，full也不符合
                            continue;
                        }
                        if(dis.compareTo(reductionAmount) >= 0){
                            reductionAmount = dis;
                            finishReductionActivity = reductionActivity;
                            fRules = reductionRuleList.get(0);
                            fRules.setActivityType(reductionActivity.getActivityType());
                            fRules.setActivityMode(reductionActivity.getActivityMode());
                        }
                    }

//                    for (ReductionRules rules : reductionRuleList) {
//                        if(!reductionActivity.getActivityType().equals("AAL") && rules.getFull() == null) {
//                            continue;
//                        }
//                        if(reductionActivity.getActivityType().equals("AAL") || rules.getFull() <= compareNum){
//                            //达到满减金额
//                            if(reductionActivity.getActivityType().equals("AAL")){
//                                if((BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount) >= 0){
//                                    reductionAmount = BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }else{
//                                if(BigDecimal.valueOf(rules.getCut()).compareTo(reductionAmount) >= 0){
//                                    reductionAmount = BigDecimal.valueOf(rules.getCut());
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }
//                        }
//                    }
                }else if(reductionActivity.getActivityMode().equals("PAR")){
                    //百分比立减

                    for (ReductionRules rules : reductionRuleList) {
                        Double full = rules.getFull();
                        BigDecimal dis;
                        //每升立减逻辑
                        if(Constant.REDUCTION_ACTIVITY_TYPE_LITRE.equals(reductionActivity.getActivityType())
                                || Constant.REDUCTION_ACTIVITY_TYPE_LITRE_BY_LITRE.equals(reductionActivity.getActivityType())){
                            // 旧活动的full为空，需要判断一下
                            if(full == null || full <= compareNum){
                                dis = BigDecimal.valueOf(amt).multiply(BigDecimal.valueOf(rules.getCut())).multiply(new BigDecimal("0.01")).setScale(2,RoundingMode.HALF_UP);
                            }else{
                                dis = BigDecimal.ZERO;
                            }
                        }else if(full != null && full <= compareNum){
                            // 其它活动类型逻辑
                            dis = BigDecimal.valueOf(amt).multiply(BigDecimal.valueOf(rules.getCut())).multiply(new BigDecimal("0.01")).setScale(2,RoundingMode.HALF_UP);
                        }else {
                            //既不是每升立减，full也不符合
                            continue;
                        }
                        if(dis.compareTo(reductionAmount) >= 0){
                            reductionAmount = dis;
                            finishReductionActivity = reductionActivity;
                            fRules = reductionRuleList.get(0);
                            fRules.setActivityType(reductionActivity.getActivityType());
                            fRules.setActivityMode(reductionActivity.getActivityMode());
                        }
                    }

//                    for (ReductionRules rules : reductionRuleList) {
//                        if(!reductionActivity.getActivityType().equals("AAL") && rules.getFull() == null)continue;
//                        if(reductionActivity.getActivityType().equals("AAL") || rules.getFull() <= compareNum){
//                            if(reductionActivity.getActivityType().equals("AAL")){
//                                //按照订单金额及升数 优惠金额是每升优惠金额，所以最终优惠需要乘以升数
//                                if((new BigDecimal(amt).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2)
//                                        .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount)>=0){
//                                    BigDecimal oil=new BigDecimal(amt).divide(new BigDecimal(payOrder.getOrderLiters()),2, BigDecimal.ROUND_HALF_UP);
//                                    reductionAmount = oil.multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100)).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
//                                    finishReductionActivity = reductionActivity;
////                                    reductionAmount = new BigDecimal(amt).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2)
////                                            .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
//
//                                }
//                            }else{
//                                //达到满减金额
//                                if((new BigDecimal(amt).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2)).compareTo(reductionAmount)>=0){
////                                  先人错误写法，启示后人1是浮点型2是参数少了      reductionAmount = new BigDecimal(amt).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2);
////                                  BigDecimal   reductionAmount1 =(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2);
//                                    log.info("rules.getCut(){}",rules.getCut());
//                                    BigDecimal   reductionAmount2 = new BigDecimal(String.valueOf(rules.getCut())).multiply(new BigDecimal("0.01"));
//                                    log.info("reductionAmount2{}",reductionAmount2);
//                                    reductionAmount = new BigDecimal(amt).multiply(reductionAmount2).setScale(2, BigDecimal.ROUND_HALF_UP);
//                                    log.info("reductionAmount{}",reductionAmount);
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }
//
//                        }
//                    }
                }else if(reductionActivity.getActivityMode().equals("RDD")){
                    //随机立减
                    for (ReductionRules rules : reductionRuleList) {
                        if(!reductionActivity.getActivityType().equals("AAL") && rules.getFull() == null)continue;
                        if(reductionActivity.getActivityType().equals("AAL") || rules.getFull() <= compareNum){
                            //达到满减金额
                            Double random = Math.random()*rules.getCutMax()+rules.getCutMin();
                            if(random > rules.getCutMax()) random = rules.getCutMax();

                            if(reductionActivity.getActivityType().equals("AAL")){
                                //按照订单金额及升数 优惠金额是每升优惠金额，所以最终优惠需要乘以升数
                                if((new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)
                                        .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount)>=0){
                                    reductionAmount = new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)
                                            .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
                                    if(new BigDecimal(reductionActivity.getBudget().toString()).compareTo(reductionAmount) < 0){
                                        //预算不足
                                        reductionAmount = new BigDecimal(reductionActivity.getBudget().toString());
                                    }
                                    finishReductionActivity = reductionActivity;
                                    fRules = reductionRuleList.get(0);
                                    fRules.setActivityType(reductionActivity.getActivityType());
                                    fRules.setActivityMode(reductionActivity.getActivityMode());
                                }
                            }else{
                                if((new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount)>=0){
                                    reductionAmount = new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP).setScale(2,BigDecimal.ROUND_HALF_UP);
                                    if(new BigDecimal(reductionActivity.getBudget().toString()).compareTo(reductionAmount) < 0){
                                        //预算不足
                                        reductionAmount = new BigDecimal(reductionActivity.getBudget().toString());
                                    }
                                    finishReductionActivity = reductionActivity;
                                    fRules = reductionRuleList.get(0);
                                    fRules.setActivityType(reductionActivity.getActivityType());
                                    fRules.setActivityMode(reductionActivity.getActivityMode());
                                }
                            }

                        }
                    }
                }
            }
//            if(finishReductionActivity == null){
//                return BigDecimal.ZERO;
//            }
            Map<String,Object> result = new HashMap<String,Object>();
            if(finishReductionActivity != null){
                //拿到最终优惠金额 reductionAmount 和最终采取的立减活动 finishReductionActivity
                if(finishReductionActivity.getActivityMode().equals("RDD")){
                    //随机立减，预算减少
                    finishReductionActivity.setBudget(finishReductionActivity.getBudget() - Double.valueOf(reductionAmount.toString()));
                    reductionActivityMapper.updateReductionActivity(finishReductionActivity);
                }
                ReductionActivityLog reductionActivityLog = new ReductionActivityLog();
                reductionActivityLog.setCreateTime(now);
                reductionActivityLog.setCreateUser(Long.valueOf(appUserInfos.getUserId()));
                reductionActivityLog.setCutAmount(Double.valueOf(reductionAmount.toString()));
                reductionActivityLog.setOrderId(Long.valueOf(payOrder.getOrderId()));
                reductionActivityLog.setReductionActivityId(finishReductionActivity.getActivityId());
                reductionActivityLog.setUserId(Long.valueOf(appUserInfos.getUserId()));
                reductionActivityLogMapper.insertReductionActivityLog(reductionActivityLog);
                result.put("activityRule",finishReductionActivity.getActivityRule());
                result.put("rule",fRules);
            }

            List<CouponUser> couponList;
            if (StringUtils.equals("2",payOrderRequest.getCardFlag()) && Objects.equals(stationInfos.getCouponDzkExclusiveFlag(),0)) {
                // 电子卡支付，且油站电子卡优惠劵互斥开关开启
                couponList = Collections.emptyList();
            }else{
                couponList=getCouponList(stationInfos,appUserInfos,oilId,stationId,payMode,amt,reductionAmount,finishReductionActivity,payOrderRequest.getNewCreatefalg());
            }
            result.put("reductionAmount",reductionAmount);
            result.put("couponList",couponList);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("reductionAmount",BigDecimal.ZERO);
            result.put("couponList",null);
            return result;
        }
    }

    @Override
    public boolean checkActivityPayMethod(ReductionActivity activity,String payType,String dzkCardType,String physicalCardOilType,String physicalCardType){
        if (StringUtils.equals("all", activity.getMemberCondition())) {
            return true;
        }
        // 车主条件非全部判断支付方式
        if (!StringUtils.equalsAny(payType, PayTypeEnum.dzk.getType(),PayTypeEnum.dkq.getType())) {
            // 非实体卡，电子卡支付，判断是否设置了支付方式
            // 活动设置的支付方式不包含，跳过
            return StringUtils.contains(activity.getPaymentMethod(), payType);
        }else if (StringUtils.equals(payType, PayTypeEnum.dzk.getType())){
            // 判断电子卡类型，只有电子卡支付才判断
            // 为空，或不包含卡类型跳过
            return !StringUtils.isEmpty(activity.getCardType()) && StringUtils.contains(activity.getCardType(), dzkCardType);
        }else if(StringUtils.equals(payType,PayTypeEnum.dkq.getType())){
            // 判断实体卡类型，只有实体卡支付才判断
            // 为空，或不包含卡类型跳过
            return !StringUtils.isEmpty(activity.getPhysicalCardType())
                    && ( StringUtils.contains(activity.getPhysicalCardType(), physicalCardOilType)
                    || StringUtils.contains(activity.getPhysicalCardType(), physicalCardType) );
        }
        return true;
    }

    public List<CouponUser> getCouponList(Station stationInfos,AppUserInfo appUserInfos,String oilId,Integer stationId,String payMode,Double amt,BigDecimal reductionAmount,ReductionActivity finishReductionActivity,String newCreatefalg){
        List<CouponUser> couponList = new ArrayList<CouponUser>();
        if(null !=stationInfos.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfos.getEnterprise().getCouponEnabledFlag())){
            CouponUser couponUser = null;
            couponUser = new CouponUser();
            couponUser.setEnterpriseId(appUserInfos.getStationId());
            couponUser.setMobilePhone(appUserInfos.getMobilePhone());
            couponUser.setOilId(oilId);
            couponUser.setStationId(stationId);
            couponUser.setCouponThresholdAmt(new BigDecimal(amt.toString()));
            couponUser.setPayType(payMode);
            //使用是不判断用户等级和是否是超级会员
//                if(appUserSuperDetail != null){
//                    couponUser.setSuperId(appUserSuperDetail.getSuperId());
//                }
//                couponUser.setMemberLevel(userGrade);
            amt = amt - reductionAmount.doubleValue();
            //优化    取消掉优惠卷的判断
            if(!"1".equals(newCreatefalg)) {
                if (finishReductionActivity != null) {
                    if (finishReductionActivity.getActivityRule().equals("1")) {
                        //立减活动不强制，可以查询不互斥的优惠券
                        couponUser.setActivityFlag("0");//已经有立减活动，查询不互斥的优惠券
                        couponList = couponMapper.selectUsefulCoupon(couponUser);
                    }
                } else {
                    couponList = couponMapper.selectUsefulCoupon(couponUser);
                }
            }
            else {
                couponList = couponMapper.selectUsefulCoupon(couponUser);
            }
            //couponList = couponMapper.selectUsefulCoupon(couponUser);
            //加上充值活动送的优惠券
            //List<CouponUser> list=couponMapper.selectCZHDUsefulCoupon(couponUser);
            //couponList.addAll(list);
        }

        if(couponList != null && couponList.size() > 0){
            for (CouponUser user : couponList) {
                if(user.getCouponType().equals("1")){
                    //现金
                    user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt()));
                }else if(user.getCouponType().equals("2")){
                    //折扣
                    user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt().multiply(new BigDecimal(amt.toString())).divide(new BigDecimal(100), 2)));
                }
                if(user.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
                    user.setNewAmtByCoupon(new BigDecimal("0.01"));
                }
            }

            Collections.sort(couponList, new Comparator<CouponUser>() {
                @Override
                public int compare(CouponUser o1, CouponUser o2) {
                    //升序
                    return o1.getNewAmtByCoupon().compareTo(o2.getNewAmtByCoupon());
                }
            });
        }


        return couponList;
    }

    /**
     * 获取一个用户已支付订单id，没有表示新用户
     * @param appUserInfo
     * @return
     */
    @Override
    public Integer getUserOrderId(AppUserInfo appUserInfo){
        AppUserInfo userInfoForm = new AppUserInfo();
        userInfoForm.setStationId(appUserInfo.getStationId());
        if (StringUtils.isNotBlank(appUserInfo.getMobilePhone())) {
            userInfoForm.setMobilePhone(appUserInfo.getMobilePhone());
        }else if(appUserInfo.getUserId() != null){
            userInfoForm.setUserId(appUserInfo.getUserId());
        }else{
            return null;
        }
        Integer orderId = payOrderMapper.getOneUserPaidOrderId(userInfoForm);
        if (orderId != null) {
            return orderId;
        }
        return payOrderHistoryMapper.getOneUserPaidOrderId(userInfoForm);
    }

    @Override
    public boolean checkDayTime(ReductionActivity reductionActivity,int week,int month,LocalTime nowTime){
        // 判断当天时间  false不在区间 true 在区间
        boolean inActivityTime = true;
        String timeMode = reductionActivity.getTimeMode();
        if (!StringUtils.equals("all", timeMode)) {
            String days = reductionActivity.getDays();
            String weeks = reductionActivity.getWeeks();
            if (StringUtils.equals("week",timeMode)) {
                // 仅按周判断
                String seaStr;
                if (StringUtils.isNotBlank(weeks)) {
                    seaStr = weeks;
                }else{
                    // 兼容旧数据
                    seaStr = days;
                }
                String[] split = seaStr.split(",");
                List<Integer> weekList = Arrays.stream(split).map(Integer::valueOf).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                inActivityTime = checkWeekTime(reductionActivity, weekList, week, nowTime);
            }else if(StringUtils.equals("month",timeMode)){
                // 仅按月判断
                String[] split = days.split(",");
                List<Integer> monthList = Arrays.stream(split).map(Integer::valueOf).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                inActivityTime = checkMonthTime(reductionActivity,monthList,month,nowTime);
            }else{
                // 周月同时判断
                String[] split = days.split(",");
                List<Integer> monthList = Arrays.stream(split).map(Integer::valueOf).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                split = weeks.split(",");
                List<Integer> weekList = Arrays.stream(split).map(Integer::valueOf).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                int ms = monthList.size()-1;
                int ws = weekList.size()-1;
                int wi = weekList.indexOf(week);
                int mi = monthList.indexOf(month);
                if(mi == -1 && wi >=0){
                    // 仅符合周条件
                    inActivityTime = checkWeekTime(reductionActivity,weekList,week,nowTime);
                }else if(wi == -1 && mi >=0){
                    // 仅符合月条件
                    inActivityTime = checkMonthTime(reductionActivity,monthList,month,nowTime);
                }else if(wi == 0 && mi == ms){
                    // 周匹配到第一天，且，月匹配到最后一天，有一个符合就可以
                    inActivityTime = checkWeekTime(reductionActivity,weekList,week,nowTime);
                    inActivityTime = inActivityTime || checkMonthTime(reductionActivity,monthList,month,nowTime);
                }else if(mi == 0 && wi == ws){
                    // 月匹配到第一天，且，周匹配到最后一天，有一个符合就可以
                    inActivityTime = checkMonthTime(reductionActivity,monthList,month,nowTime);
                    inActivityTime = inActivityTime || checkWeekTime(reductionActivity,weekList,week,nowTime);
                }else if(wi == 0 && mi == 0){
                    // 周月同时匹配到第一天，有一个符合就可以
                    inActivityTime = checkWeekTime(reductionActivity,weekList,week,nowTime);
                    inActivityTime = inActivityTime || checkMonthTime(reductionActivity,monthList,month,nowTime);
                }else if(wi == ws && mi == ms){
                    // 周月同时匹配到最后一天，有一个符合就可以
                    inActivityTime = checkWeekTime(reductionActivity,weekList,week,nowTime);
                    inActivityTime = inActivityTime || checkMonthTime(reductionActivity,monthList,month,nowTime);
                }
//                else{
//                    // 只有一个匹配到边界，或都没有匹配到边界
//                }
            }
        }
        return inActivityTime;
    }


    private boolean checkWeekTime(ReductionActivity reductionActivity,List<Integer> weekList,int week,LocalTime nowTime){
        // false不在区间 true 在区间
        boolean r = true;
        Integer wf = weekList.get(0);
        Integer wl = weekList.get(weekList.size() - 1);
        if(reductionActivity.getWeekTimeRangeType().equals(ReductionActivity.TIMERANGEVALIDITYTYPE_ENTIRE)){
            if(weekList.size() == 1 && wf == week){
                // 首天和最后一天是同一天，判断是否区间外，取反
                r = !( nowTime.isBefore(reductionActivity.getStartTimeOfWeek()) || nowTime.isAfter(reductionActivity.getEndTimeOfWeek()) );
            }else if(week == wf){
                // 首天，判单当前时间是否小于周开始时间
                if (nowTime.isBefore(reductionActivity.getStartTimeOfWeek())) {
                    // 小于，不在
                    r = false;
                }
            }else if(week == wl){
                // 最后一天，判单当前时间是否大于周结束时间
                if (nowTime.isAfter(reductionActivity.getEndTimeOfWeek())) {
                    // 大于，不在
                    r = false;
                }
            }
        }else if(reductionActivity.getWeekTimeRangeType().equals(ReductionActivity.TIMERANGEVALIDITYTYPE_EACH)){
            if(nowTime.isBefore(reductionActivity.getStartTimeOfWeek())||nowTime.isAfter(reductionActivity.getEndTimeOfWeek())){
                r = false;
            }
        }
        return r;
    }

    private boolean checkMonthTime(ReductionActivity reductionActivity,List<Integer> monthList,int month, LocalTime nowTime){
        boolean r = true;
        Integer mf = monthList.get(0);
        Integer ml = monthList.get(monthList.size() - 1);
        if(reductionActivity.getMonthTimeRangeType().equals(ReductionActivity.TIMERANGEVALIDITYTYPE_ENTIRE)){
            if(monthList.size() == 1 && mf == month){
                // 首天和最后一天是同一天，判断是否区间外，取反
                r = !( nowTime.isBefore(reductionActivity.getStartTimeOfMonth()) || nowTime.isAfter(reductionActivity.getEndTimeOfMonth()) );
            }else if(month == mf){
                // 首天，判单当前时间是否小于周开始时间
                if (nowTime.isBefore(reductionActivity.getStartTimeOfMonth())) {
                    // 小于，不在
                    r = false;
                }
            }else if(month == ml){
                // 最后一天，判单当前时间是否大于周结束时间
                if (nowTime.isAfter(reductionActivity.getEndTimeOfMonth())) {
                    // 大于，不在
                    r = false;
                }
            }
        }else if(reductionActivity.getMonthTimeRangeType().equals(ReductionActivity.TIMERANGEVALIDITYTYPE_EACH)){
            if(nowTime.isBefore(reductionActivity.getStartTimeOfMonth())||nowTime.isAfter(reductionActivity.getEndTimeOfMonth())){
                r = false;
            }
        }
        return r;
    }


    //优化   通过优惠卷的id优惠
    @Override
    public Map<String,Object> selectReductionByPayOrderCoupon(AppUserInfo appUserInfos, PayOrder payOrder, String activityUse,
                                                        PayOrderRequest payOrderRequest,Station stationInfos, StaOilGun staOilGun) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmt = new SimpleDateFormat("yyyy-MM-dd");

        try{

            String payMode = payOrderRequest.getPayType();
            String labelId = payOrderRequest.getLabelId();
            String  labelName=null;

            Integer stationId = payOrder.getStationId();//油站id
            //查询用户等级
            String userGrade = "0";
            UserVirtualGradeRel virtualGradeRel = userVirtualGradeRelService.queryUserVirtualGrade(Long.valueOf(payOrder.getEnterpriseId()),
                    Long.valueOf(appUserInfos.getUserId()),LocalDateTime.now());
            if (virtualGradeRel != null) {
                userGrade = virtualGradeRel.getGradeCode();
            }else{
                Grade grade = new Grade();
                grade.setGradeGrowValue(appUserInfos.getGrowUpValue());
                grade.setEnterpriseId(Long.valueOf(appUserInfos.getStationId()));
                grade.setDeleteFlag("0");
                List<Grade> grades = gradeMapper.selectUserGrade(grade);
                if(grades != null && grades.size() == 1){
                    if(grades.get(0).getGradeCode() != null) userGrade = grades.get(0).getGradeCode();
                }
            }
            appUserInfos.setUserLevel(userGrade);
            // 判断是不是超级会员
            Date now = new Date();
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                    .enterpriseId(Long.valueOf(appUserInfos.getStationId()))
                    .userId(Long.valueOf(appUserInfos.getUserId()))
                    .beginDate(now)
                    .endDate(now)
                    .build());
            if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
                //有记录，是超级会员
                AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(appUserSuperDetails.get(0).getSuperId());
                if (appUserSuper != null) {
                    appUserInfos.setSuperUser(MEMBER_LEVEL_MAP.get(appUserSuper.getSuperName()));
                }
                //appUserInfos.setSuperUser(Constant.MEMBER_LEVEL_SUPER);
            }else{
                // 不是
                appUserInfos.setSuperUser(null);
            }
            String memberCategory = "new";
            Integer userOrderId = getUserOrderId(appUserInfos);
            if (userOrderId != null) {
                memberCategory = "old";
            }

            String oilId;
            if (payOrderRequest.getOilId() == null) {
                oilId = String.valueOf(staOilGun.getOil().getOilId());
            }else{
                oilId = String.valueOf(payOrderRequest.getOilId());
            }
//            oilId = "3";//TODO delete
            //计算优惠
            //  BigDecimal orderLiters = new BigDecimal(payOrder.getOrderLiters());//加油升数
            List<ReductionActivity> labreductionActivities = new ArrayList<ReductionActivity>();
            List<ReductionActivity> reductionActivities = new ArrayList<ReductionActivity>();
            //判断用户标签
            Map<String,Object> labelParams = new HashMap<String,Object>();
            // 当为电子卡支付，跳过标签判断，走电子卡自带的优惠
       /*     if (!"1".equals(payOrderRequest.getCardFlag())){*/
                //标签用户，强制使用标签优惠
                if(StringUtils.isNotEmpty(labelId)){
                    //根据标签id判断标签和关联的活动，判断标签是否是当前油企的
                    LabelRule labelRule = new LabelRule();
                    labelRule.setLabelId(Integer.valueOf(labelId));
                    labelRule.setDelFlag("0");
                    labelRule.setEnterpriseId(appUserInfos.getStationId());
                    List<LabelRule> labelRuleList = labelMapper.getLabelRuleList(labelRule);
                    if(labelRuleList != null && labelRuleList.size() == 1){
                        LabelRule label = labelRuleList.get(0);
                        if(StringUtils.isNotEmpty(label.getActivityIds())){
                            labelParams.put("activityIds",label.getActivityIds());
                            labelParams.put("stationId",stationId);
                            labelParams.put("oilId",oilId);
                            labelParams.put("activityUse","LABEl");
                            labelParams.put("memberLevel",userGrade);
                            labelParams.put("superUser",appUserInfos.getSuperUser());
                            labelParams.put("currentDate",fmt.format(now));
                            labelParams.put("paymentMethod",payMode);
                            labelParams.put("memberCategory",memberCategory);
                            if(payOrderRequest.getCouponNo()!=null&&!"".equals(payOrderRequest.getCouponNo())) {
                                labelParams.put("activityRule", 1);
                            }
                            List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
                            if(labelReductionActivities != null && labelReductionActivities.size() == 1){
                                labreductionActivities.add(labelReductionActivities.get(0));
                                labelName=label.getLabelName();
                            }
                        }
                        if(label.getIsAddLabel().equals("1")){
                            //强制添加的标签，判断用户有没有标签，有就更新标签id 没有就新增标签
                            CustomerLabel customerLabel = new CustomerLabel();
                            customerLabel.setPhone(appUserInfos.getMobilePhone());
                            customerLabel.setEnterpriseId(appUserInfos.getStationId());
                            CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                            if(userLabel != null){
                                //修改标签
                                userLabel.setLabelId(labelId);
                                labelMapper.updateCustomerLabel(userLabel);
                            }
                            else{
                                //新增标签
                                userLabel = new CustomerLabel();
                                userLabel.setLabelId(labelId);
                                userLabel.setDelFlag("0");
                                userLabel.setEnterpriseId(appUserInfos.getStationId());
                                userLabel.setPhone(appUserInfos.getMobilePhone());
                                userLabel.setCreateBy(String.valueOf(appUserInfos.getUserId()));
                                userLabel.setCreateTime(now);
                                userLabel.setUpdateBy(String.valueOf(appUserInfos.getUserId()));
                                userLabel.setUpdateTime(now);
                                userLabel.setStationId(stationId);
                                labelMapper.insertCustomerLabel(userLabel);
                            }
                        }
                    }
                    else{
                        //根据传入labelId没有查询到有效的标签，根据用户和油企查询是否有标签
                        CustomerLabel customerLabel = new CustomerLabel();
                        customerLabel.setPhone(appUserInfos.getMobilePhone());
                        customerLabel.setEnterpriseId(appUserInfos.getStationId());
                        CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                        if(userLabel != null){
                            labelRule = new LabelRule();
                            labelRule.setLabelId(Integer.valueOf(userLabel.getLabelId()));
                            labelRule.setDelFlag("0");
                            labelRule.setEnterpriseId(appUserInfos.getStationId());
                            //   优化   这个的接口的关联表没有用
                            labelRuleList = labelMapper.getLabelRuleList(labelRule);
                            if(labelRuleList != null && labelRuleList.size() == 1){
                                LabelRule label = labelRuleList.get(0);
                                if(StringUtils.isNotEmpty(label.getActivityIds())){
                                    labelParams.put("activityIds",label.getActivityIds());
                                    labelParams.put("stationId",stationId);
                                    labelParams.put("oilId",oilId);
                                    labelParams.put("activityUse","LABEl");
                                    labelParams.put("memberLevel",userGrade);
                                    labelParams.put("superUser",appUserInfos.getSuperUser());
                                    labelParams.put("currentDate",fmt.format(now));
                                    labelParams.put("paymentMethod",payMode);
                                    labelParams.put("memberCategory",memberCategory);
                                    //通过优惠券取消立减活动
                                    if(payOrderRequest.getCouponNo()!=null&&!"".equals(payOrderRequest.getCouponNo())) {
                                        labelParams.put("activityRule", 1);
                                    }
                                    List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
                                    if(labelReductionActivities != null && labelReductionActivities.size() == 1){
                                        labreductionActivities.add(labelReductionActivities.get(0));
                                        labelName=label.getLabelName();
                                    }
                                }
                            }
                        }
                    }
                }
                else{
                    //没有传入标签id，根据用户和油企查询是否有标签
                    //根据传入labelId没有查询到有效的标签，根据用户和油企查询是否有标签
                    CustomerLabel customerLabel = new CustomerLabel();
                    customerLabel.setPhone(appUserInfos.getMobilePhone());
                    customerLabel.setEnterpriseId(appUserInfos.getStationId());
                    CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                    if(userLabel != null){
                        LabelRule labelRule = new LabelRule();
                        labelRule.setLabelId(Integer.valueOf(userLabel.getLabelId()));
                        labelRule.setDelFlag("0");
                        labelRule.setEnterpriseId(appUserInfos.getStationId());
                        List<LabelRule> labelRuleList = labelMapper.getLabelRuleList(labelRule);
                        if(labelRuleList != null && labelRuleList.size() == 1){
                            LabelRule label = labelRuleList.get(0);
                            if(StringUtils.isNotEmpty(label.getActivityIds())){
                                labelParams.put("activityIds",label.getActivityIds());
                                labelParams.put("stationId",stationId);
                                labelParams.put("oilId",oilId);
                                labelParams.put("activityUse","LABEl");
                                labelParams.put("memberLevel",userGrade);
                                labelParams.put("superUser",appUserInfos.getSuperUser());
                                labelParams.put("currentDate",fmt.format(now));
                                labelParams.put("paymentMethod",payMode);
                                labelParams.put("memberCategory",memberCategory);
                                if(payOrderRequest.getCouponNo()!=null&&!"".equals(payOrderRequest.getCouponNo())) {
                                    labelParams.put("activityRule", 1);
                                }
                                List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
                                if(labelReductionActivities != null && labelReductionActivities.size() == 1){
                                    labreductionActivities.add(labelReductionActivities.get(0));
                                    labelName=label.getLabelName();
                                }
                            }
                        }
                    }
                }
        /*    }*/
            Map<String,Object> queryMap = new HashMap<String,Object>();
            for (ReductionActivity reductionActivity : labreductionActivities) {
                queryMap.clear();
                queryMap.put("userId",appUserInfos.getUserId());
                queryMap.put("reductionActivityId",reductionActivity.getActivityId());
                queryMap.put("startDate",simFmt.format(now)+" 00:00:00");
                queryMap.put("endDate",simFmt.format(now)+" 23:59:59");

                Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
                if(reductionActivity.getMaxCount() != 0){
                    Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
                    if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                        //超出单次活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getAntiCheating().equals("0")){
                    Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
                    //开启了每日次数限制
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                else{
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getActivityMode().equals("RDD")){
                    if(reductionActivity.getBudget() <= 0){
                        //预算不足
                        continue;
                    }
                }
                reductionActivities.add(reductionActivity);
            }
            Double amt = payOrder.getReceivableAmt();//实收金额
            queryMap.clear();
            queryMap.put("stationId",stationId);
            queryMap.put("oilId",oilId);
            queryMap.put("activityUse","CSP");
            queryMap.put("memberLevel",userGrade);
            queryMap.put("superUser",appUserInfos.getSuperUser());
            queryMap.put("paymentMethod",payMode);
            queryMap.put("currentDate",fmt.format(now));
            queryMap.put("enterpriseId",appUserInfos.getStationId());
            queryMap.put("cardFlag",payOrderRequest.getCardFlag());
            queryMap.put("memberCategory",memberCategory);
            //优化     确定用户不是标签用户
            Calendar calendar = Calendar.getInstance();
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            int month = calendar.get(Calendar.DAY_OF_MONTH);
            if(week == 1){
                week = 7;
            }else{
                week--;
            }
            if(reductionActivities.size() == 0){
                //优化   超级会员的立减活动
//                AppUserSuperDetail appUserSuperDetail = null;
//                List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
//                        .enterpriseId(Long.valueOf(appUserInfos.getStationId().toString()))
//                        .userId(Long.valueOf(appUserInfos.getUserId().toString())).beginDate(now).endDate(now).build());
//                if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
//                    appUserSuperDetail = appUserSuperDetails.get(0);
//                    Long superId = appUserSuperDetail.getSuperId();
//                    AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(superId);
//                    if(appUserSuper != null && appUserSuper.getActivityId() != null){
//                        labelParams.put("activityId",appUserSuper.getActivityId());
//                        labelParams.put("stationId",stationId);
//                        labelParams.put("oilId",oilId);
//                        labelParams.put("activityUse","CSP");
//                        labelParams.put("currentDate",fmt.format(now));
//                        if(payOrderRequest.getCouponNo()!=null&&!"".equals(payOrderRequest.getCouponNo())) {
//                            labelParams.put("activityRule", 1);
//                        }
//                        List<ReductionActivity> labelReductionActivities = reductionActivityMapper.selectByOrderInfo(labelParams);
//                        if(labelReductionActivities != null && labelReductionActivities.size() == 1){
//                            reductionActivities.add(labelReductionActivities.get(0));
//                        }
//                    }
//                }

                //计算当前是周几以及几号，查询时间是否符合
                queryMap.put("week",week);
                queryMap.put("month",month);
                //根据优惠卷编码，判断是否筛选互斥的优惠活动
                if(payOrderRequest.getCouponNo()!=null&&!"".equals(payOrderRequest.getCouponNo())) {
                    queryMap.put("activityRule", 1);
                }
                reductionActivities.addAll(queryOldActivityByDayAndWeek(queryMap));
            }

            ReductionRules reductionRules = null;
            ReductionOilRelations reductionOilRelations = null;
            List<ReductionRules> reductionRuleList = new ArrayList<ReductionRules>();
            ReductionActivity finishReductionActivity = null;
            BigDecimal reductionAmount = BigDecimal.ZERO;
            Double compareNum = 0D;
            reductionActivities=checkLabelUser(reductionActivities,appUserInfos.getMobilePhone(),appUserInfos.getStationId().longValue());
            LocalTime nowTime = LocalTime.now();
            String oilCardType = staOilGun.getOil().getCardType();
            if (Boolean.TRUE.equals(payOrderRequest.getGenericPay())) {
                oilCardType = ElectronCardType.GENERIC.getKey();
            }
            ReductionRules fRules = null;
            for (ReductionActivity reductionActivity : reductionActivities) {

                // 判断支付方式
                if (!checkActivityPayMethod(reductionActivity, payMode,oilCardType,null,null)) {
                    continue;
                }

                //判断金额是否超过活动上限
                if(isAmtUpperLimit(reductionActivity,BigDecimal.valueOf(payOrder.getReceivableAmt()))){
                    continue;
                }

                // 判断时间
                if (!checkDayTime(reductionActivity,week,month,nowTime)) {
                    continue;
                }

                reductionRules = new ReductionRules();
                // 查询该活动的限制
                queryMap.clear();
                queryMap.put("userId",appUserInfos.getUserId());
                queryMap.put("reductionActivityId",reductionActivity.getActivityId());
                queryMap.put("startDate",simFmt.format(now)+" 00:00:00");
                queryMap.put("endDate",simFmt.format(now)+" 23:59:59");
                Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
                if(reductionActivity.getMaxCount() != 0){
                    Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
                    if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                        //超出单次活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getAntiCheating().equals("0")){
                    Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
                    //开启了每日次数限制
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }else{
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getActivityType().equals("RFA")){
                    compareNum = amt;
                }else if(reductionActivity.getActivityType().equals("LOR")){
                    compareNum = Double.valueOf(payOrder.getOrderLiters());
                }else if(reductionActivity.getActivityType().equals("AAL")){
                    //按照订单金额及升数
                    compareNum = amt;
                }else if(reductionActivity.getActivityType().equals(Constant.REDUCTION_ACTIVITY_TYPE_LITRE_BY_LITRE)){
                    // 每升立减-按升数
                    compareNum = Double.valueOf(payOrder.getOrderLiters());
                }
                System.out.println(reductionActivity.getActivityName());
                Long oilPartOrAll = reductionActivity.getOilPartOrAll();
                if(oilPartOrAll == 1){
                    //针对全部油品，规则直接关联活动
                    reductionRules.setActivityId(reductionActivity.getActivityId());
                    reductionRuleList = reductionRulesMapper.selectReductionRulesList(reductionRules);
                }else{
                    //针对部分油品，规则关联油品
                    reductionOilRelations = new ReductionOilRelations();
                    reductionOilRelations.setActivityId(reductionActivity.getActivityId());
                    reductionOilRelations.setOilId(Long.valueOf( payOrder.getOilId()));
                    List<ReductionOilRelations> reductionOilRelationsList = reductionOilRelationsMapper.selectReductionOilRelationsList(reductionOilRelations);
                    if(reductionOilRelationsList != null && reductionOilRelationsList.size() == 1){
                        reductionOilRelations = reductionOilRelationsList.get(0);
                        reductionRules.setActivityOilId(reductionOilRelations.getActivityOilId());
                        reductionRuleList = reductionRulesMapper.selectReductionRulesList(reductionRules);
                    }
                }
                //判断立减类型
                if(reductionActivity.getActivityMode().equals("FAD")){
                    //定额立减

                    for (ReductionRules rules : reductionRuleList) {
                        Double full = rules.getFull();
                        BigDecimal dis;
                        //每升立减逻辑
                        if(Constant.REDUCTION_ACTIVITY_TYPE_LITRE.equals(reductionActivity.getActivityType())
                                || Constant.REDUCTION_ACTIVITY_TYPE_LITRE_BY_LITRE.equals(reductionActivity.getActivityType())){
                            // 旧活动的full为空，需要判断一下
                            if(full == null || full <= compareNum){
                                dis = BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2, RoundingMode.HALF_UP);
                            }else{
                                dis = BigDecimal.ZERO;
                            }
                        }else if(full != null && full <= compareNum){
                            // 其它活动类型逻辑
                            dis = BigDecimal.valueOf(rules.getCut());
                        }else{
                            //既不是每升立减，full也不符合
                            continue;
                        }
                        if(dis.compareTo(reductionAmount) >= 0){
                            reductionAmount = dis;
                            finishReductionActivity = reductionActivity;
                            fRules = reductionRuleList.get(0);
                            fRules.setActivityType(reductionActivity.getActivityType());
                            fRules.setActivityMode(reductionActivity.getActivityMode());
                        }
                    }

//                    for (ReductionRules rules : reductionRuleList) {
//                        if(!reductionActivity.getActivityType().equals("AAL") && rules.getFull() == null)continue;
//                        if(reductionActivity.getActivityType().equals("AAL") || rules.getFull() <= compareNum){
//                            //达到满减金额
//                            if(reductionActivity.getActivityType().equals("AAL")){
//                                if((BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount) >= 0){
//                                    reductionAmount = BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }else{
//                                if(BigDecimal.valueOf(rules.getCut()).compareTo(reductionAmount) >= 0){
//                                    reductionAmount = BigDecimal.valueOf(rules.getCut());
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }
//                        }
//                    }
                }else if(reductionActivity.getActivityMode().equals("PAR")){
                    //百分比立减

                    for (ReductionRules rules : reductionRuleList) {
                        Double full = rules.getFull();
                        BigDecimal dis;
                        //每升立减逻辑
                        if(Constant.REDUCTION_ACTIVITY_TYPE_LITRE.equals(reductionActivity.getActivityType())
                                || Constant.REDUCTION_ACTIVITY_TYPE_LITRE_BY_LITRE.equals(reductionActivity.getActivityType())){
                            // 旧活动的full为空，需要判断一下
                            if(full == null || full <= compareNum){
                                dis = BigDecimal.valueOf(amt).multiply(BigDecimal.valueOf(rules.getCut())).multiply(new BigDecimal("0.01")).setScale(2,RoundingMode.HALF_UP);
                            }else{
                                dis = BigDecimal.ZERO;
                            }
                        }else if(full != null && full <= compareNum){
                            // 其它活动类型逻辑
                            dis = BigDecimal.valueOf(amt).multiply(BigDecimal.valueOf(rules.getCut())).multiply(new BigDecimal("0.01")).setScale(2,RoundingMode.HALF_UP);
                        }else {
                            //既不是每升立减，full也不符合
                            continue;
                        }
                        if(dis.compareTo(reductionAmount) >= 0){
                            reductionAmount = dis;
                            finishReductionActivity = reductionActivity;
                            fRules = reductionRuleList.get(0);
                            fRules.setActivityType(reductionActivity.getActivityType());
                            fRules.setActivityMode(reductionActivity.getActivityMode());
                        }
                    }

//                    for (ReductionRules rules : reductionRuleList) {
//                        if(!reductionActivity.getActivityType().equals("AAL") && rules.getFull() == null)continue;
//                        if(reductionActivity.getActivityType().equals("AAL") || rules.getFull() <= compareNum){
////                            if(reductionActivity.getActivityType().equals("AAL")){
//                            if(reductionActivity.getActivityType().equals("AAL")){
//                                //按照订单金额及升数 优惠金额是每升优惠金额，所以最终优惠需要乘以升数
//                                if((new BigDecimal(amt).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2)
//                                        .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount)>=0){
//
//
//                                    BigDecimal oil=new BigDecimal(amt).divide(new BigDecimal(payOrder.getOrderLiters()),2, BigDecimal.ROUND_HALF_UP);
//                                    reductionAmount = oil.multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100)).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }else{
//                                //达到满减金额
//                                if((new BigDecimal(amt).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2)).compareTo(reductionAmount)>=0){
//                                    BigDecimal   reductionAmount2 = new BigDecimal(String.valueOf(rules.getCut())).multiply(new BigDecimal("0.01"));
//                                    reductionAmount = new BigDecimal(amt).multiply(reductionAmount2).setScale(2, BigDecimal.ROUND_HALF_UP);
//
//                                    finishReductionActivity = reductionActivity;
//                                }
//                            }
//
//                        }
//                    }
                }else if(reductionActivity.getActivityMode().equals("RDD")){
                    //随机立减
                    for (ReductionRules rules : reductionRuleList) {
                        if(!reductionActivity.getActivityType().equals("AAL") && rules.getFull() == null)continue;
                        if(reductionActivity.getActivityType().equals("AAL") || rules.getFull() <= compareNum){
                            //达到满减金额
                            Double random = Math.random()*rules.getCutMax()+rules.getCutMin();
                            if(random > rules.getCutMax()) random = rules.getCutMax();

                            if(reductionActivity.getActivityType().equals("AAL")){
                                //按照订单金额及升数 优惠金额是每升优惠金额，所以最终优惠需要乘以升数
                                if((new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)
                                        .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount)>=0){
                                    reductionAmount = new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)
                                            .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
                                    if(new BigDecimal(reductionActivity.getBudget().toString()).compareTo(reductionAmount) < 0){
                                        //预算不足
                                        reductionAmount = new BigDecimal(reductionActivity.getBudget().toString());
                                    }
                                    finishReductionActivity = reductionActivity;
                                    fRules = reductionRuleList.get(0);
                                    fRules.setActivityType(reductionActivity.getActivityType());
                                    fRules.setActivityMode(reductionActivity.getActivityMode());
                                }
                            }else{
                                if((new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)).compareTo(reductionAmount)>=0){
                                    reductionAmount = new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP).setScale(2,BigDecimal.ROUND_HALF_UP);
                                    if(new BigDecimal(reductionActivity.getBudget().toString()).compareTo(reductionAmount) < 0){
                                        //预算不足
                                        reductionAmount = new BigDecimal(reductionActivity.getBudget().toString());
                                    }
                                    finishReductionActivity = reductionActivity;
                                    fRules = reductionRuleList.get(0);
                                    fRules.setActivityType(reductionActivity.getActivityType());
                                    fRules.setActivityMode(reductionActivity.getActivityMode());
                                }
                            }

                        }
                    }
                }
            }
//            if(finishReductionActivity == null){
//                return BigDecimal.ZERO;
//            }
            // 将之前立减活动的日志全部删除，
//            ReductionActivityLog reductionActivityLog1=new ReductionActivityLog();
//            reductionActivityLog1.setOrderId(Long.valueOf(payOrder.getOrderId()));
//            List<ReductionActivityLog> reductionActivityLogs=reductionActivityLogMapper.selectReductionActivityLogList(reductionActivityLog1);
//            if(reductionActivityLogs!=null&&reductionActivityLogs.size()>0){
//                for(ReductionActivityLog reductionActivityLog:reductionActivityLogs){
//                    reductionActivityLogMapper.deleteReductionActivityLogById(reductionActivityLog.getReductionActivityLogId());
//                }
//            }



            List<CouponUser> couponList;

            if(null !=stationInfos.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfos.getEnterprise().getCouponEnabledFlag())){
                if (StringUtils.equals("2",payOrderRequest.getCardFlag()) && Objects.equals(stationInfos.getCouponDzkExclusiveFlag(),0)) {
                    // 电子卡支付，且油站电子卡优惠劵互斥开关开启
                    couponList = Collections.emptyList();
                    payOrderRequest.setCouponNo(null);
                    payOrderRequest.setCouponUserId(null);
                }else{
                    CouponUser couponUser = null;
                    couponUser = new CouponUser();
                    couponUser.setEnterpriseId(appUserInfos.getStationId());
                    couponUser.setMobilePhone(appUserInfos.getMobilePhone());
                    couponUser.setOilId(oilId);
                    couponUser.setStationId(stationId);
                    couponUser.setCouponThresholdAmt(new BigDecimal(amt.toString()));
                    couponUser.setPayType(payMode);
                    //使用是不判断用户等级和是否是超级会员
//                if(appUserSuperDetail != null){
//                    couponUser.setSuperId(appUserSuperDetail.getSuperId());
//                }
//                couponUser.setMemberLevel(userGrade);
//                amt = amt - reductionAmount.doubleValue();
                    //优化    取消掉优惠卷的判断
//                if(finishReductionActivity != null){
//                    if(finishReductionActivity.getActivityRule().equals("1")){
//                        //立减活动不强制，可以查询不互斥的优惠券
//                        couponUser.setActivityFlag("0");//已经有立减活动，查询不互斥的优惠券
//                        couponList = couponMapper.selectUsefulCoupon(couponUser);
//                    }
//                }else{
//                    couponList = couponMapper.selectUsefulCoupon(couponUser);
//                }
                    couponList = couponMapper.selectUsefulCoupon(couponUser);
                }
            }else{
                couponList = Collections.emptyList();
                payOrderRequest.setCouponNo(null);
                payOrderRequest.setCouponUserId(null);
            }
            if(couponList != null && couponList.size() > 0){
                for (CouponUser user : couponList) {
                    if(user.getCouponType().equals("1")){
                        //现金
                        user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt()));
                    }else if(user.getCouponType().equals("2")){
                        //折扣
                        user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt().multiply(new BigDecimal(amt.toString())).divide(new BigDecimal(100), 2)));
                    }
                    if(user.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
                        user.setNewAmtByCoupon(new BigDecimal("0.01"));
                    }
                }
                Collections.sort(couponList, new Comparator<CouponUser>() {
                    @Override
                    public int compare(CouponUser o1, CouponUser o2) {
                        //升序
                        return o1.getNewAmtByCoupon().compareTo(o2.getNewAmtByCoupon());
                    }
                });
            }
            BigDecimal couponAmount=BigDecimal.ZERO;
            if(payOrderRequest.getCouponNo()!=null&&!"".equals(payOrderRequest.getCouponNo())) {
                //List<CouponUser> couponUsers = couponMapper.selectUsefulCoupon(CouponUser.builder().couponNo(payOrderRequest.getCouponNo()).build());
                List<CouponUser> couponUsers = couponMapper.selectUsefulCoupon(CouponUser.builder().couponUserId(Integer.valueOf(payOrder.getCouponUserId())).build());
                if (couponUsers != null && couponUsers.size() > 0) {
                    if ("1".equals(couponUsers.get(0).getCouponType())) {
                        couponAmount = couponUsers.get(0).getCouponAmt();
                    }
                    if ("2".equals(couponUsers.get(0).getCouponType())) {
                        //TODO 这里的优惠券折扣的金额是按照，优惠后的金额来计算
                        couponAmount = new BigDecimal(payOrder.getReceivableAmt()).subtract(reductionAmount).multiply(couponUsers.get(0).getCouponAmt().divide(new BigDecimal(100), 2));
                        //reductionAmount.add(new BigDecimal(payOrder.getReceivableAmt()).multiply(couponUsers.get(0).getCouponAmt().divide(new BigDecimal(100), 2)));
                    }
                    if("1".equals(couponUsers.get(0).getActivityFlag())){
                        reductionAmount=BigDecimal.ZERO;
                        finishReductionActivity=null;

                    }
                }

            }
            if (payOrder.getOrderId() != null) {
                reductionActivityLogMapper.deleteReductionActivityLogByOrderId(Long.valueOf(payOrder.getOrderId()));
                if(finishReductionActivity != null){
                    //拿到最终优惠金额 reductionAmount 和最终采取的立减活动 finishReductionActivity
                    if(finishReductionActivity.getActivityMode().equals("RDD")){
                        //随机立减，预算减少
                        finishReductionActivity.setBudget(finishReductionActivity.getBudget() - Double.valueOf(reductionAmount.toString()));
                        reductionActivityMapper.updateReductionActivity(finishReductionActivity);
                    }
                    ReductionActivityLog reductionActivityLog = new ReductionActivityLog();
                    reductionActivityLog.setCreateTime(now);
                    reductionActivityLog.setCreateUser(Long.valueOf(appUserInfos.getUserId()));
                    reductionActivityLog.setCutAmount(Double.valueOf(reductionAmount.toString()));
                    reductionActivityLog.setOrderId(Long.valueOf(payOrder.getOrderId()));
                    reductionActivityLog.setReductionActivityId(finishReductionActivity.getActivityId());
                    reductionActivityLog.setUserId(Long.valueOf(appUserInfos.getUserId()));
                    reductionActivityLogMapper.insertReductionActivityLog(reductionActivityLog);
                }
            }

            Map<String,Object> result = new HashMap<String,Object>();
            result.put("reductionAmount",reductionAmount);
            if(finishReductionActivity!=null) {
                result.put("activityId", finishReductionActivity.getActivityId());
                result.put("activityRule",finishReductionActivity.getActivityRule());
            }
            result.put("labelId",labelId);
            result.put("labelName",labelName);
            result.put("couponAmount",couponAmount);
            result.put("couponList",couponList);
            result.put("rule",fRules);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("reductionAmount",BigDecimal.ZERO);
            result.put("couponList",null);
            return result;
        }
    }
    public CouponUser getDiscountMaxCoupon(BigDecimal amt,List<CouponUser> couponUsers,String mobilePhone){
        if(amt!=null&&couponUsers!=null&&couponUsers.size()>0){
            for (CouponUser couponUser : couponUsers) {
                BigDecimal couponAmount=BigDecimal.ZERO;
                if ("1".equals(couponUser.getCouponType())) {
                    couponAmount = couponUser.getCouponAmt();
                }
                if ("2".equals(couponUser.getCouponType())) {
                    //TODO 这里的优惠券折扣的金额是按照，优惠后的金额来计算
                    couponAmount = amt.multiply(couponUser.getCouponAmt().divide(new BigDecimal(100), 2));
                    //reductionAmount.add(new BigDecimal(payOrder.getReceivableAmt()).multiply(couponUsers.get(0).getCouponAmt().divide(new BigDecimal(100), 2)));
                }
                couponUser.setFinalCouponAmount(couponAmount);
            }
            List<CouponUser> collect = couponUsers.stream().filter(couponUser -> couponUser.getFinalCouponAmount().compareTo(amt) <= 0).collect(Collectors.toList());
            collect = collect.stream().sorted(Comparator.comparing(CouponUser::getFinalCouponAmount).reversed()).collect(Collectors.toList());
            if(collect.size()==0){
                return null;
            }
            for (CouponUser item : collect){
                PayOrderRequest request = new PayOrderRequest();
                request.setMobilePhone(mobilePhone);
                request.setCouponUserId(item.getCouponUserId().toString());
                Map<String, Object> a= payOrderService.cherkCouponCount(request);
                if(a.get("status").equals("2")){
                    String msg = a.get("msg").toString();
                    continue;
                }
                return item;
            }
            return null;
        }


        return null;
    }

    @Override
    public Map<String,Object> selectReductionAndCouponByPayOrder(AppUserInfo appUserInfos, PayOrder payOrder, String activityUse,
                                                                 PayOrderRequest payOrderRequest,Station stationInfos) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmt = new SimpleDateFormat("yyyy-MM-dd");

        try{

            String payMode = payOrderRequest.getPayType();
            String labelId = payOrderRequest.getLabelId();

            Integer stationId = payOrder.getStationId();//油站id
            //查询用户等级
            String userGrade = "0";
            Grade grade = new Grade();
            grade.setGradeGrowValue(appUserInfos.getGrowUpValue());
            grade.setEnterpriseId(Long.valueOf(appUserInfos.getStationId()));
            grade.setDeleteFlag("0");
            List<Grade> grades = gradeMapper.selectUserGrade(grade);
            if(grades != null && grades.size() == 1){
                if(grades.get(0).getGradeCode() != null) userGrade = grades.get(0).getGradeCode();
            }

            //查询用户有没有支付过，支付过就是老用户，没有就是新用户
            List<PayOrder> userOrderListByUnionId = payOrderMapper.getUserOrderListByUnionId(appUserInfos);
            String memberTags = "newUser";
            if(userOrderListByUnionId != null && userOrderListByUnionId.size()>0)memberTags = "oldUser";
            String oilId = payOrder.getOilName();
//            oilId = "3";//TODO delete
            //计算优惠
            BigDecimal orderLiters = new BigDecimal(payOrder.getOrderLiters());//加油升数
            List<ReductionActivity> labreductionActivities = new ArrayList<ReductionActivity>();
            List<ReductionActivity> reductionActivities = new ArrayList<ReductionActivity>();
            //判断用户标签
            if(StringUtils.isNotEmpty(labelId)){
                //根据标签id判断标签和关联的活动，判断标签是否是当前油企的
                LabelRule labelRule = new LabelRule();
                labelRule.setLabelId(Integer.valueOf(labelId));
                labelRule.setDelFlag("0");
                labelRule.setEnterpriseId(appUserInfos.getStationId());
                List<LabelRule> labelRuleList = labelMapper.getLabelRuleList(labelRule);
                if(labelRuleList != null && labelRuleList.size() == 1){
                    LabelRule label = labelRuleList.get(0);
                    if(StringUtils.isNotEmpty(label.getActivityIds())){
                        List<ReductionActivity> reductionActivitys = reductionActivityMapper.selectReductionActivityByIds(label.getActivityIds());
                        if(reductionActivitys.size()>0){
                            labreductionActivities.addAll(reductionActivitys);
                        }
                    }
                    if(label.getIsAddLabel().equals("1")){
                        //强制添加的标签，判断用户有没有标签，有就更新标签id 没有就新增标签
                        CustomerLabel customerLabel = new CustomerLabel();
                        customerLabel.setPhone(appUserInfos.getMobilePhone());
                        customerLabel.setEnterpriseId(appUserInfos.getStationId());
                        CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                        if(userLabel != null){
                            //修改标签
                            userLabel.setLabelId(labelId);
                            labelMapper.updateCustomerLabel(userLabel);
                        }else{
                            //新增标签
                            userLabel = new CustomerLabel();
                            userLabel.setLabelId(labelId);
                            userLabel.setDelFlag("0");
                            userLabel.setEnterpriseId(appUserInfos.getStationId());
                            userLabel.setPhone(appUserInfos.getMobilePhone());
                            userLabel.setCreateBy(String.valueOf(appUserInfos.getUserId()));
                            userLabel.setCreateTime(new Date());
                            userLabel.setUpdateBy(String.valueOf(appUserInfos.getUserId()));
                            userLabel.setUpdateTime(new Date());
                            userLabel.setStationId(stationId);
                            labelMapper.insertCustomerLabel(userLabel);
                        }
                    }
                }else{
                    //根据传入labelId没有查询到有效的标签，根据用户和油企查询是否有标签
                    CustomerLabel customerLabel = new CustomerLabel();
                    customerLabel.setPhone(appUserInfos.getMobilePhone());
                    customerLabel.setEnterpriseId(appUserInfos.getStationId());
                    CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                    if(userLabel != null){
                        labelRule = new LabelRule();
                        labelRule.setLabelId(Integer.valueOf(userLabel.getLabelId()));
                        labelRule.setDelFlag("0");
                        labelRule.setEnterpriseId(appUserInfos.getStationId());
                        labelRuleList = labelMapper.getLabelRuleList(labelRule);
                        if(labelRuleList != null && labelRuleList.size() == 1){
                            LabelRule label = labelRuleList.get(0);
                            if(StringUtils.isNotEmpty(label.getActivityIds())){
                                List<ReductionActivity> reductionActivitys = reductionActivityMapper.selectReductionActivityByIds(label.getActivityIds());
                                if(reductionActivitys.size()>0){
                                    labreductionActivities.addAll(reductionActivitys);
                                }
                            }
                        }
                    }
                }
            }else{
                //没有传入标签id，根据用户和油企查询是否有标签
                //根据传入labelId没有查询到有效的标签，根据用户和油企查询是否有标签
                CustomerLabel customerLabel = new CustomerLabel();
                customerLabel.setPhone(appUserInfos.getMobilePhone());
                customerLabel.setEnterpriseId(appUserInfos.getStationId());
                CustomerLabel userLabel = labelMapper.getCustomerLabel(customerLabel);
                if(userLabel != null){
                    LabelRule labelRule = new LabelRule();
                    labelRule.setLabelId(Integer.valueOf(userLabel.getLabelId()));
                    labelRule.setDelFlag("0");
                    labelRule.setEnterpriseId(appUserInfos.getStationId());
                    List<LabelRule> labelRuleList = labelMapper.getLabelRuleList(labelRule);
                    if(labelRuleList != null && labelRuleList.size() == 1){
                        LabelRule label = labelRuleList.get(0);
                        if(StringUtils.isNotEmpty(label.getActivityIds())){
                            List<ReductionActivity> reductionActivitys = reductionActivityMapper.selectReductionActivityByIds(label.getActivityIds());
                            if(reductionActivitys.size()>0){
                                labreductionActivities.addAll(reductionActivitys);
                            }
                        }
                    }
                }
            }
            Map<String,Object> queryMap = new HashMap<String,Object>();
            for (ReductionActivity reductionActivity : labreductionActivities) {
                queryMap.clear();
                queryMap.put("userId",appUserInfos.getUserId());
                queryMap.put("reductionActivityId",reductionActivity.getActivityId());
                queryMap.put("startDate",simFmt.format(new Date())+" 00:00:00");
                queryMap.put("endDate",simFmt.format(new Date())+" 23:59:59");
                Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
                if(reductionActivity.getMaxCount() != 0){
                    Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
                    if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                        //超出单次活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getAntiCheating().equals("0")){
                    Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
                    //开启了每日次数限制
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }else{
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                reductionActivities.add(reductionActivity);
            }
            Double amt = payOrder.getAmt();//实收金额
            queryMap.clear();
            queryMap.put("stationId",stationId);
            queryMap.put("oilId",oilId);
            queryMap.put("activityUse","CSP");
            //queryMap.put("memberLevel",userGrade);
            //queryMap.put("memberTags",memberTags);
            queryMap.put("paymentMethod",payMode);
            queryMap.put("currentDate",fmt.format(new Date()));
            queryMap.put("enterpriseId",appUserInfos.getStationId());
            if(reductionActivities.size() == 0){
                AppUserSuperDetail appUserSuperDetail = null;
                List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                        .enterpriseId(Long.valueOf(appUserInfos.getStationId().toString()))
                        .userId(Long.valueOf(appUserInfos.getUserId().toString())).beginDate(new Date()).endDate(new Date()).build());
                if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
                    appUserSuperDetail = appUserSuperDetails.get(0);
                    Long superId = appUserSuperDetail.getSuperId();
                    AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(superId);
                    if(appUserSuper != null && appUserSuper.getActivityId() != null){
                        ReductionActivity reductionActivity = reductionActivityMapper.selectReductionActivityById(appUserSuper.getActivityId());
                        if(reductionActivity != null){
                            reductionActivities.add(reductionActivity);
                        }
                    }
                }

                //计算当前是周几以及几号，查询时间是否符合
                Calendar calendar = Calendar.getInstance();
                int week = calendar.get(Calendar.DAY_OF_WEEK);
                int month = calendar.get(Calendar.DAY_OF_MONTH);
                if(week == 1){
                    week = 7;
                }else{
                    week--;
                }
                queryMap.put("week",week);
                queryMap.put("month",month);
                queryMap.put("cardFlag",payOrderRequest.getCardFlag());
                reductionActivities.addAll(queryOldActivityByDayAndWeek(queryMap));
            }

            ReductionRules reductionRules = null;
            ReductionOilRelations reductionOilRelations = null;
            List<ReductionRules> reductionRuleList = null;
            List<ReductionActivity> reductionActivityList = new ArrayList<ReductionActivity>();
            BigDecimal reductionAmount = BigDecimal.ZERO;
            Double compareNum = 0D;
            for (ReductionActivity reductionActivity : reductionActivities) {
                reductionRules = new ReductionRules();
                // 查询该活动的限制
                queryMap.clear();
                queryMap.put("userId",appUserInfos.getUserId());
                queryMap.put("reductionActivityId",reductionActivity.getActivityId());
                queryMap.put("startDate",simFmt.format(new Date())+" 00:00:00");
                queryMap.put("endDate",simFmt.format(new Date())+" 23:59:59");
                Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
                if(reductionActivity.getMaxCount() != 0){
                    Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
                    if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                        //超出单次活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getAntiCheating().equals("0")){
                    Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
                    //开启了每日次数限制
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }else{
                    if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                        //超出单日活动最大参与次数限制
                        continue;
                    }
                }
                if(reductionActivity.getActivityType().equals("RFA")){
                    compareNum = amt;
                }else if(reductionActivity.getActivityType().equals("LOR")){
                    compareNum = Double.valueOf(payOrder.getOrderLiters());
                }else if(reductionActivity.getActivityType().equals("AAL")){
                    //按照订单金额及升数
                    compareNum = amt;
                }
                System.out.println(reductionActivity.getActivityName());
                Long oilPartOrAll = reductionActivity.getOilPartOrAll();
                if(oilPartOrAll == 1){
                    //针对全部油品，规则直接关联活动
                    reductionRules.setActivityId(reductionActivity.getActivityId());
                    reductionRuleList = reductionRulesMapper.selectReductionRulesList(reductionRules);
                }else{
                    //针对部分油品，规则关联油品
                    reductionOilRelations = new ReductionOilRelations();
                    reductionOilRelations.setActivityId(reductionActivity.getActivityId());
                    reductionOilRelations.setOilId(Long.valueOf(oilId));
                    List<ReductionOilRelations> reductionOilRelationsList = reductionOilRelationsMapper.selectReductionOilRelationsList(reductionOilRelations);
                    if(reductionOilRelationsList != null && reductionOilRelationsList.size() == 1){
                        reductionOilRelations = reductionOilRelationsList.get(0);
                        reductionRules.setActivityOilId(reductionOilRelations.getActivityOilId());
                        reductionRuleList = reductionRulesMapper.selectReductionRulesList(reductionRules);
                    }
                }


                for (ReductionRules rules : reductionRuleList) {
                    if(rules.getFull() == null)continue;
                    if(rules.getFull() <= compareNum){
                        reductionActivity.setReductionRule(rules);
                    }
                }
                reductionActivityList.add(reductionActivity);

            }

            List<CouponUser> couponList = null;
            if(null !=stationInfos.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfos.getEnterprise().getCouponEnabledFlag())){
                CouponUser couponUser = null;
                couponUser = new CouponUser();
                couponUser.setEnterpriseId(appUserInfos.getStationId());
                couponUser.setMobilePhone(appUserInfos.getMobilePhone());
                couponUser.setOilId(oilId);
                couponUser.setStationId(stationId);
                couponUser.setCouponThresholdAmt(new BigDecimal(amt.toString()));
                couponUser.setPayType(payMode);

                couponList = couponMapper.selectUsefulCoupon(couponUser);
            }
            if(couponList != null){
                for (CouponUser user : couponList) {
                    if(user.getCouponType().equals("1")){
                        //现金
                        user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt()));
                    }else if(user.getCouponType().equals("2")){
                        //折扣
                        user.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(user.getCouponAmt().multiply(new BigDecimal(amt.toString())).divide(new BigDecimal(100), 2)));
                    }
                    if(user.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
                        user.setNewAmtByCoupon(new BigDecimal("0.01"));
                    }
                }
                Collections.sort(couponList, new Comparator<CouponUser>() {
                    @Override
                    public int compare(CouponUser o1, CouponUser o2) {
                        //升序
                        return o1.getNewAmtByCoupon().compareTo(o2.getNewAmtByCoupon());
                    }
                });
            }

            Map<String,Object> result = new HashMap<String,Object>();
            result.put("reductionActivityList",reductionActivityList);
            result.put("couponList",couponList);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("reductionActivityList",null);
            result.put("couponList",null);
            return result;
        }
    }

    @Override
    public BigDecimal selectVisitorReductionByPayOrder(BigDecimal amt, PayOrder payOrder, AppUserInfo appUserInfo) {
        ReductionActivitiesVO activitiesVO=new ReductionActivitiesVO();
        activitiesVO.setActivityUse("CSP");
        activitiesVO.setAmt(amt);
        activitiesVO.setDateTime(LocalDateTimeUtil.parse(LocalDateTime.now()));
        activitiesVO.setEnterpriseId(payOrder.getEnterpriseId());
        activitiesVO.setOilId(Integer.valueOf(payOrder.getOilName()));
        activitiesVO.setOrderLiters(payOrder.getOrderLiters());
        activitiesVO.setStationId(payOrder.getStationId());
        // 抓不到用户信息的默认老用户
        activitiesVO.setMemberCategory(Constant.MEMBER_CATEGORY_OLD_USER);
        BigDecimal discountAmt=payOrderService.reductionActivitiesAmountCalculation(activitiesVO,null).setScale(2, RoundingMode.HALF_UP);
        //amt=amt.subtract(discountAmt);//计算参与活动之后的实付款金额
        if(amt.subtract(discountAmt).compareTo(DecimalConstant.O_01)<=0) {
            //amt=BigDecimal.valueOf(0.01);
            discountAmt = amt.subtract(DecimalConstant.O_01);
        }
        if(activitiesVO.getActivityId()!=null) {
            //更新活动的预算，避免多个用户同时支付时，产生超预算的问题
            this.updateReductionActivityBudget(discountAmt.negate(), activitiesVO.getActivityId());
            appUserInfo.setFRules(activitiesVO.getFRules());
        }
        return discountAmt;
    }

    @Override
    public PayOrder calculateCouponAndActivity(PayOrder payOrder){
        //TODO 验证立减活动和优惠券是否有效和当前用户是否符合条件
        Long activityId = payOrder.getActivityId();              //立减活动id
        String discountCoupon = payOrder.getDiscountCoupon();       //优惠券id
        ReductionActivity reductionActivity = null;
        CouponUser couponUser = null;
        if(activityId == null){
            payOrder.setDiscountAmt(0D);
        }else{
            reductionActivity = reductionActivityMapper.selectReductionActivityById(activityId.longValue());
        }
        if(discountCoupon == null){
            payOrder.setDiscountCouponAmt(0D);
        }else{
            //查询优惠券
            CouponUser couponUserParam = null;
            couponUserParam = new CouponUser();
            //主要根据优惠券id查询，其他条件是为了限制其有效性
            couponUserParam.setCouponUserId(Integer.valueOf(payOrder.getDiscountCoupon()));
            couponUserParam.setMobilePhone(payOrder.getCustomerPhone());
            couponUserParam.setOilId(payOrder.getOilId().toString());    //订单油品ID 该订单信息获取方法名：payOrderService.selectOrderInfoByOrdNo(ordNo);
            couponUserParam.setStationId(payOrder.getStationId());
            //使用门槛用应付金额来判断
            couponUserParam.setCouponThresholdAmt(new BigDecimal(payOrder.getReceivableAmt()));
            couponUserParam.setPayType(payOrder.getPayType());
            List<CouponUser> couponList = couponMapper.selectUsefulCoupon(couponUserParam);
            if(couponList != null && couponList.size()>0){
                couponUser = couponList.get(0);
            }
        }
        //判断优惠券和立减活动哪个是互斥 如果有一个互斥的就只计算互斥的那个，放弃另一个。如果有两个互斥的，就计算立减活动，放弃计算优惠券
        if(reductionActivity != null && ((couponUser == null || couponUser.getActivityFlag().equals("0")) ||
                (reductionActivity.getReductionRule().equals("2") && couponUser.getActivityFlag().equals("1")))){
            //计算立减
            if(payOrder.getReceivableAmt() > 0.01){
                Double compareNum = 0D;
                BigDecimal reductionAmount = BigDecimal.ZERO;
                ReductionRules rules = reductionRulesMapper.selectReductionRulesById(payOrder.getRulesId());
                if(reductionActivity.getActivityType().equals("RFA")){
                    compareNum = payOrder.getReceivableAmt();
                }else if(reductionActivity.getActivityType().equals("LOR")){
                    compareNum = Double.valueOf(payOrder.getOrderLiters());
                }else if(reductionActivity.getActivityType().equals("AAL")){
                    //按照订单金额及升数
                    compareNum = payOrder.getReceivableAmt();
                }
                //判断立减类型
                if(reductionActivity.getActivityMode().equals("FAD")){
                    //定额立减
                    if(rules.getFull() <= compareNum){
                        //达到满减金额
                        if(reductionActivity.getActivityType().equals("AAL")){
                            reductionAmount = BigDecimal.valueOf(rules.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
                        }else{
                            reductionAmount = BigDecimal.valueOf(rules.getCut());
                        }
                    }
                }else if(reductionActivity.getActivityMode().equals("PAR")){
                    //百分比立减
                    if(rules.getFull() <= compareNum){
                        if(reductionActivity.getActivityType().equals("AAL")){
                            //按照订单金额及升数 优惠金额是每升优惠金额，所以最终优惠需要乘以升数
                            reductionAmount = new BigDecimal(payOrder.getReceivableAmt()).multiply(new BigDecimal(rules.getCut())).divide(new BigDecimal(100), 2)
                                    .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
                        }else{
                            //达到满减金额
                            BigDecimal   reductionAmount2 = new BigDecimal(rules.getCut()).multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_HALF_UP);
                            reductionAmount = new BigDecimal(payOrder.getReceivableAmt()).multiply(reductionAmount2).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }

                    }
                }else if(reductionActivity.getActivityMode().equals("RDD")){
                    //随机立减
                    if(rules.getFull() <= compareNum){
                        //达到满减金额
                        Double random = Math.random()*rules.getCutMax()+rules.getCutMin();
                        if(random > rules.getCutMax()) random = rules.getCutMax();

                        if(reductionActivity.getActivityType().equals("AAL")){
                            //按照订单金额及升数 优惠金额是每升优惠金额，所以最终优惠需要乘以升数
                            reductionAmount = new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP)
                                    .multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2,BigDecimal.ROUND_HALF_UP);
                            if(new BigDecimal(reductionActivity.getBudget().toString()).compareTo(reductionAmount) < 0){
                                //预算不足
                                reductionAmount = new BigDecimal(reductionActivity.getBudget().toString());
                            }
                        }else{
                            reductionAmount = new BigDecimal(random).setScale(2,BigDecimal.ROUND_HALF_UP).setScale(2,BigDecimal.ROUND_HALF_UP);
                            if(new BigDecimal(reductionActivity.getBudget().toString()).compareTo(reductionAmount) < 0){
                                //预算不足
                                reductionAmount = new BigDecimal(reductionActivity.getBudget().toString());
                            }
                        }
                    }
                }
                //防止出现低于0.01的实付
                if((new BigDecimal(payOrder.getReceivableAmt()).subtract(reductionAmount)).compareTo(new BigDecimal("0.01"))<=0){
                    reductionAmount = new BigDecimal(payOrder.getReceivableAmt()).subtract(new BigDecimal("0.01"));
                }
                payOrder.setActivityId(reductionActivity.getActivityId());
                payOrder.setDiscountAmt(reductionAmount.doubleValue());
                BigDecimal amt = new BigDecimal(payOrder.getReceivableAmt()).subtract(reductionAmount);
                payOrder.setAmt(amt.doubleValue());
                payOrder.setDzkAmt(amt.doubleValue());

                //记录或修改日志
                ReductionActivityLog reductionActivityLogParam =  new ReductionActivityLog();
                reductionActivityLogParam.setOrderId(payOrder.getOrderId().longValue());
                List<ReductionActivityLog> reductionActivityLogs = reductionActivityLogMapper.selectReductionActivityLogList(reductionActivityLogParam);
                if(reductionActivityLogs != null && reductionActivityLogs.size() == 1){
                    ReductionActivityLog reductionActivityLog = reductionActivityLogs.get(0);
                    reductionActivityLog.setReductionActivityId(reductionActivity.getActivityId());
                    reductionActivityLog.setCutAmount(Double.valueOf(reductionAmount.toString()));
                    reductionActivityLogMapper.updateReductionActivityLog(reductionActivityLog);
                }else{
                    ReductionActivityLog reductionActivityLog = new ReductionActivityLog();
                    reductionActivityLog.setCreateTime(new Date());
                    reductionActivityLog.setCreateUser(payOrder.getConsumerId().longValue());
                    reductionActivityLog.setCutAmount(Double.valueOf(reductionAmount.toString()));
                    reductionActivityLog.setOrderId(Long.valueOf(payOrder.getOrderId()));
                    reductionActivityLog.setReductionActivityId(reductionActivity.getActivityId());
                    reductionActivityLog.setUserId(payOrder.getConsumerId().longValue());
                    reductionActivityLogMapper.insertReductionActivityLog(reductionActivityLog);
                }
            }else{
                // 放弃使用立减活动
                payOrder.setDiscountAmt(0D);
                payOrder.setActivityId(null);
            }
        }else{
            // 放弃使用立减活动
            payOrder.setDiscountAmt(0D);
            payOrder.setActivityId(null);
        }
        if(couponUser != null && (reductionActivity == null || reductionActivity.getActivityRule().equals("1"))){
            //计算优惠券
            if(payOrder.getAmt() > 0.01){
                BigDecimal subtract = null;
                if(couponUser.getCouponType().equals("1")){
                    //现金
                    subtract = couponUser.getCouponAmt();
                }else if(couponUser.getCouponType().equals("2")){
                    //折扣
                    subtract = couponUser.getCouponAmt().multiply(new BigDecimal(payOrder.getReceivableAmt())).divide(new BigDecimal(100), 2);
                }
                if(new BigDecimal(payOrder.getAmt()).subtract(subtract).compareTo(new BigDecimal("0.01"))<=0){
                    subtract = new BigDecimal(payOrder.getAmt()).subtract(new BigDecimal("0.01"));
                }
                payOrder.setDiscountCoupon(couponUser.getCouponUserId().toString());
                payOrder.setDiscountCouponAmt(subtract.doubleValue());
                BigDecimal amt = new BigDecimal(payOrder.getAmt()).subtract(subtract);
                payOrder.setAmt(amt.doubleValue());
                payOrder.setDzkAmt(amt.doubleValue());
            }else {
                // 放弃使用优惠券
                payOrder.setDiscountCouponAmt(0D);
                payOrder.setDiscountCoupon(null);
            }
        }else{
            payOrder.setDiscountCouponAmt(0D);
            payOrder.setDiscountCoupon(null);
        }
        //防止修改到不明确的内容，单独只修改这几列
        PayOrder p = new PayOrder();
        p.setOrderId(payOrder.getOrderId());
        p.setDiscountAmt(payOrder.getDiscountAmt());
        p.setDiscountCoupon(payOrder.getDiscountCoupon());
        p.setDiscountCouponAmt(payOrder.getDiscountCouponAmt());
        p.setActivityId(payOrder.getActivityId());
        p.setDzkAmt(payOrder.getDzkAmt());
        p.setAmt(payOrder.getAmt());
        payOrderMapper.updateByPrimaryKeySelective(p);
        return payOrder;
    }

    /**
     * 校验订单中优惠券是否可用，并且计算优惠金额以及优惠后金额
     *
     * @param appUserInfos
     * @param payOrder
     * @param stationInfos
     * @return 用户优惠券
     */
    @Override
    public CouponUser checkCoupon(AppUserInfo appUserInfos, PayOrder payOrder, Station stationInfos){
        //查询该订单使用的立减活动 用来判断是否互斥，是否可以使用优惠券
        //  优化  根据当前订单内的立减活动的id来进行判断，不用之前的日志
//        ReductionActivityLog reductionActivityLogParam = new ReductionActivityLog();
//        reductionActivityLogParam.setOrderId(Long.valueOf(payOrder.getOrderId()));
//        List<ReductionActivityLog> reductionActivityLogs = reductionActivityLogMapper.selectReductionActivityLogList(reductionActivityLogParam);
        ReductionActivity reductionActivity = null;

        if(payOrder!= null && payOrder.getActivityId()!=null){
           // ReductionActivityLog reductionActivityLog = reductionActivityLogs.get(0);
            reductionActivity = reductionActivityMapper.selectReductionActivityById(payOrder.getActivityId());
        }
        Integer stationId = payOrder.getStationId();//油站id

        if(null !=stationInfos.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfos.getEnterprise().getCouponEnabledFlag())){
            CouponUser couponUser = null;
            couponUser = new CouponUser();
            //主要根据优惠券id查询，其他条件是为了限制其有效性
            couponUser.setCouponUserId(Integer.valueOf(payOrder.getDiscountCoupon()));
            couponUser.setEnterpriseId(appUserInfos.getStationId());
            couponUser.setMobilePhone(appUserInfos.getMobilePhone());
            couponUser.setOilId(payOrder.getOilId().toString());    //订单油品ID 该订单信息获取方法名：payOrderService.selectOrderInfoByOrdNo(ordNo);
            couponUser.setStationId(stationId);
            //使用门槛用应付金额来判断
            couponUser.setCouponThresholdAmt(new BigDecimal(payOrder.getReceivableAmt()));
            couponUser.setPayType(payOrder.getPayType());

            List<CouponUser> couponList = null;
            if(reductionActivity != null){
                if(reductionActivity.getActivityRule().equals("1")){
                    //立减活动不强制，可以查询不互斥的优惠券
                    couponUser.setActivityFlag("0");//已经有立减活动，查询不互斥的优惠券
                    couponList = couponMapper.selectUsefulCoupon(couponUser);
                }
            }else{
                couponList = couponMapper.selectUsefulCoupon(couponUser);
            }
            //amt为立减优惠（如有）之后的金额
            BigDecimal amt = new BigDecimal(payOrder.getAmt().toString());
            CouponUser couponUserFinish = null;
            //因为使用了用户优惠券id 所以只能查出来一条
            if(couponList != null && couponList.size() == 1){
                couponUserFinish = couponList.get(0);
            }
            if(couponUserFinish != null){
                BigDecimal subtract = null;
                if(couponUserFinish.getCouponType().equals("1")){
                    //现金
                    subtract = couponUserFinish.getCouponAmt().setScale(2,BigDecimal.ROUND_HALF_UP);
                    couponUserFinish.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(subtract));
                }else if(couponUserFinish.getCouponType().equals("2")){
                    //折扣
                    subtract = couponUserFinish.getCouponAmt().multiply(new BigDecimal(amt.toString())).divide(new BigDecimal(100), 2).setScale(2,BigDecimal.ROUND_HALF_UP);
                    couponUserFinish.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(subtract));
                }
                if(couponUserFinish.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
                    subtract = amt.subtract(new BigDecimal("0.01")).setScale(2,BigDecimal.ROUND_HALF_UP);
                    couponUserFinish.setNewAmtByCoupon(new BigDecimal("0.01"));
                }
                couponUserFinish.setCouponAmtByCNY(subtract);
                return couponUserFinish;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * 校验订单中优惠券是否可用，并且计算优惠金额以及优惠后金额
     *
     * @param appUserInfos
     * @param payOrder
     * @param stationInfos
     * @return 用户优惠券
     */
    @Override
    public CouponUser newCheckCoupon(AppUserInfo appUserInfos, PayOrder payOrder, Station stationInfos){
        //查询该订单使用的立减活动 用来判断是否互斥，是否可以使用优惠券
        //  优化  根据当前订单内的立减活动的id来进行判断，不用之前的日志
//        ReductionActivityLog reductionActivityLogParam = new ReductionActivityLog();
//        reductionActivityLogParam.setOrderId(Long.valueOf(payOrder.getOrderId()));
//        List<ReductionActivityLog> reductionActivityLogs = reductionActivityLogMapper.selectReductionActivityLogList(reductionActivityLogParam);
        ReductionActivity reductionActivity = null;

        if(payOrder!= null && payOrder.getActivityId()!=null){
            // ReductionActivityLog reductionActivityLog = reductionActivityLogs.get(0);
            reductionActivity = reductionActivityMapper.selectReductionActivityById(payOrder.getActivityId());
        }
        Integer stationId = payOrder.getStationId();//油站id

        if(null !=stationInfos.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfos.getEnterprise().getCouponEnabledFlag())){
            CouponUser couponUser = null;
            couponUser = new CouponUser();
            //主要根据优惠券id查询，其他条件是为了限制其有效性
            couponUser.setCouponUserId(Integer.valueOf(payOrder.getDiscountCoupon()));
            couponUser.setEnterpriseId(appUserInfos.getStationId());
            couponUser.setMobilePhone(appUserInfos.getMobilePhone());
            couponUser.setOilId(payOrder.getOilId().toString());    //订单油品ID 该订单信息获取方法名：payOrderService.selectOrderInfoByOrdNo(ordNo);
            couponUser.setStationId(stationId);
            //使用门槛用应付金额来判断
            couponUser.setCouponThresholdAmt(new BigDecimal(payOrder.getReceivableAmt()));
            couponUser.setPayType(payOrder.getPayType());

            List<CouponUser> couponList = null;
            if(reductionActivity != null){
                if(reductionActivity.getActivityRule().equals("1")){
                    //立减活动不强制，可以查询不互斥的优惠券
                    couponUser.setActivityFlag("0");//已经有立减活动，查询不互斥的优惠券
                    couponList = couponMapper.selectUsefulCoupon(couponUser);
                }
            }else{
                couponList = couponMapper.selectUsefulCoupon(couponUser);
            }
            //amt为立减优惠（如有）之后的金额
            BigDecimal amt = new BigDecimal(payOrder.getAmt().toString());
            CouponUser couponUserFinish = null;
            //因为使用了用户优惠券id 所以只能查出来一条
            if(couponList != null && couponList.size() == 1){
                couponUserFinish = couponList.get(0);
            }
            if(couponUserFinish != null){
                BigDecimal subtract = null;
                if(couponUserFinish.getCouponType().equals("1")){
                    //现金
                    subtract = couponUserFinish.getCouponAmt().setScale(2,BigDecimal.ROUND_HALF_UP);
                    couponUserFinish.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(subtract));
                }else if(couponUserFinish.getCouponType().equals("2")){
                    //折扣
                    subtract = couponUserFinish.getCouponAmt().multiply(new BigDecimal(amt.toString())).divide(new BigDecimal(100), 2).setScale(2,BigDecimal.ROUND_HALF_UP);
                    couponUserFinish.setNewAmtByCoupon(new BigDecimal(amt.toString()).subtract(subtract));
                }
                if(couponUserFinish.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
                    subtract = amt.subtract(new BigDecimal("0.01")).setScale(2,BigDecimal.ROUND_HALF_UP);
                    couponUserFinish.setNewAmtByCoupon(new BigDecimal("0.01"));
                }
                couponUserFinish.setCouponAmtByCNY(subtract);
                return couponUserFinish;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }
    /**
     * 查询立减活动
     *
     * @param activityId 立减活动ID
     * @return 立减活动
     */
    @Override
    public ReductionActivity selectReductionActivityById(Long activityId)
    {
        return reductionActivityMapper.selectReductionActivityById(activityId);
    }

    @Override
    public String selectReductionActivity(Integer stationId) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        List<reductionResponse> reductionActivity  =reductionStationRelationsMapper.selectReductionStationRelations(stationId,timestamp);
//        if (Objects.nonNull(reductionActivity) && reductionActivity.get)
        return null;
    }

    /**
     * 查询立减活动列表
     *
     * @param reductionActivity 立减活动
     * @return 立减活动
     */
    @Override
    public List<ReductionActivity> selectReductionActivityList(ReductionActivity reductionActivity)
    {
        return reductionActivityMapper.selectReductionActivityList(reductionActivity);
    }

    /**
     * 新增立减活动
     *
     * @param reductionActivity 立减活动
     * @return 结果
     */
    @Override
    public int insertReductionActivity(ReductionActivity reductionActivity)
    {
        return reductionActivityMapper.insertReductionActivity(reductionActivity);
    }


    /**
     * 查询立减活动的完整信息
     *
     * @param activityId 立减活动Id
     * @return 结果
     */
    @Override
    public Map<String,Object> selectActivityInfoByActivityId(Long activityId)
    {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        return resultMap;
    }

    /**
     * 修改立减活动
     *
     * @param reductionActivity 立减活动
     * @return 结果
     */
    @Override
    public int updateReductionActivity(ReductionActivity reductionActivity)
    {
        return reductionActivityMapper.updateReductionActivity(reductionActivity);
    }

    /**
     * 批量删除立减活动
     *
     * @param activityIds 需要删除的立减活动ID
     * @return 结果
     */
    @Override
    public int deleteReductionActivityByIds(Long[] activityIds)
    {
        return reductionActivityMapper.deleteReductionActivityByIds(activityIds);
    }

    /**
     * 删除立减活动信息
     *
     * @param activityId 立减活动ID
     * @return 结果
     */
    @Override
    public int deleteReductionActivityById(Long activityId)
    {
        return reductionActivityMapper.deleteReductionActivityById(activityId);
    }

	@Override
	public List<ReductionActivitiesAmountVO> selectReductionActivityStationId(ReductionActivitiesVO vo) {
		return reductionActivityMapper.selectReductionActivityStationId(vo) ;
	}

	@Override
	public int updateReductionActivityBudget(BigDecimal budget, Integer activityId) {
		return reductionActivityMapper.updateReductionActivityBudget(budget, activityId);
	}

    @Override
    public Map<String,Object> getRCHReductionAmt(AppUserInfo appUserInfos, PayOrder payOrder, PayOrderRequest payOrderRequest, Station stationInfo) {
        String userGrade = "0";
        if (StringUtils.isBlank(appUserInfos.getMemberLevel())) {
            UserVirtualGradeRel virtualGradeRel = userVirtualGradeRelService.queryUserVirtualGrade(Long.valueOf(payOrder.getEnterpriseId()),
                    Long.valueOf(appUserInfos.getUserId()),LocalDateTime.now());
            if (virtualGradeRel != null) {
                userGrade = virtualGradeRel.getGradeCode();
            }else{
                Grade grade = new Grade();
                grade.setGradeGrowValue(appUserInfos.getGrowUpValue());
                grade.setEnterpriseId(Long.valueOf(appUserInfos.getStationId()));
                grade.setDeleteFlag("0");
                List<Grade> grades = gradeMapper.selectUserGrade(grade);
                log.info("grades===={}",grades);
                if(grades != null && grades.size() == 1){
                    if(grades.get(0).getGradeCode() != null) userGrade = grades.get(0).getGradeCode();
                }
            }
            appUserInfos.setMemberLevel(userGrade);
        }else{
            userGrade = appUserInfos.getMemberLevel();
        }

        Map<String,Object> result=new HashedMap();
        BigDecimal rCHReductionAmt=BigDecimal.ZERO;
       //List<CouponUser> couponList = getCouponList(stationInfo, appUserInfos, payOrder.getOilName(), stationInfo.getStationId(), payOrderRequest.getPayType(), payOrder.getAmt(), BigDecimal.ZERO, null, payOrderRequest.getNewCreatefalg());
        List<CouponUser> couponList=new ArrayList<>();
        result.put("couponList",couponList);
        result.put("rCHReductionAmt",rCHReductionAmt);
        if(payOrderRequest.getCardFlag()!=null&&payOrderRequest.getCardFlag().equals("1")){
            //微信支付
            result.put("couponList",new ArrayList<>());
            return result;
        }
        Integer userId = appUserInfos.getUserId();
        ReductionActivityBalanceRecord recordQuery=new ReductionActivityBalanceRecord();
        //判断是汽油还是柴油
        //recordQuery.setUserId(userId.longValue());
        recordQuery.setMobilePhone(appUserInfos.getMobilePhone());
        String orderType = payOrder.getOrderType();
        if(orderType.equals("柴油")){
            recordQuery.setCardOilsType(ReductionActivityBalanceRecord.card_oils_type_diesel);
        }
        if(orderType.equals("汽油")){
            recordQuery.setCardOilsType(ReductionActivityBalanceRecord.card_oils_type_gasoline);
        }
        if(Boolean.TRUE.equals(payOrderRequest.getGenericPay())){
            recordQuery.setCardOilsType(ElectronCardType.GENERIC.getKey());
        }
        if (!StringUtils.equals("1",stationInfo.getEnterprise().getCardFlag())) {
            log.info("油企未开启电子卡油企id:{}",stationInfo.getEnterprise().getEnterpriseId());
            return result;
        }
        if (StringUtils.equals("1",stationInfo.getEnterprise().getCardUseRangeFlag())) {
            recordQuery.setEnterpriseId(stationInfo.getEnterprise().getEnterpriseId().longValue());
        }else{
            recordQuery.setStationId(stationInfo.getStationId().longValue());
        }
        List<ReductionActivityBalanceRecord> records=reductionActivityBalanceRecordService.query(recordQuery);
        if(records.size()>0){
            //有优惠余额
            ReductionActivityBalanceRecord activityBalanceRecord = records.get(0);

            //查询立减规则  activityUse：RCH  station enterpriseId
            ReductionActivity activityQuery = new ReductionActivity();
            activityQuery.setActivityUse(ReductionActivityBalanceRecord.activityType_RCH);
            activityQuery.setEnterpriseId(stationInfo.getEnterpriseId().longValue());
            activityQuery.setMemberCategory(activityBalanceRecord.getNewUserFlag());
            activityQuery.setStationId(stationInfo.getStationId().longValue());
            activityQuery.setOilId(Long.parseLong(payOrder.getOilName()));
            activityQuery.setRechargeActivityConsumeEnable(1);
            //activityQuery.setMemberLevel(userGrade);
            //activityQuery.setSuperUser(appUserInfos.getSuperUser());
            List<ReductionActivity> reductionActivities = reductionActivityMapper.selectReductionActivityList(activityQuery);
            reductionActivities = reductionActivities.stream().filter(r->checkEffectiveTime(r)).collect(Collectors.toList());
            reductionActivities=checkLabelUser(reductionActivities,appUserInfos.getMobilePhone(),stationInfo.getEnterpriseId().longValue());
            if(reductionActivities.size()>0){
                //取最新的一个
                ReductionActivity reductionActivity = reductionActivities.get(0);
                //如果有使用优惠券且 活动不能使用优惠卷  不计算立减金额
                if(reductionActivity.getActivityRule().equals("2")&&payOrder.getCouponUserId()!=null&&!payOrder.getCouponUserId().equals("")){
                    return result;
                }
//                LocalTime nowTime = LocalTime.now();
//                LocalDate localDate = LocalDate.now();
//                int week = localDate.getDayOfWeek().getValue();
//                int month = localDate.getDayOfMonth();
                // 计算立减优惠不判断时间，充值的时候判断
//                if (!checkDayTime(reductionActivity,week,month,nowTime)) {
//                    return result;
//                }

                //判断该油站是否有立减活动
                ReductionStationRelations stationRelationsQuery=new ReductionStationRelations();
                stationRelationsQuery.setActivityId(reductionActivity.getActivityId());
                stationRelationsQuery.setStationId(stationInfo.getStationId().longValue());
                List<ReductionStationRelations> reductionStationRelations = reductionStationRelationsMapper.selectReductionStationRelationsList(stationRelationsQuery);
                if(reductionStationRelations.size()==0){
                    //该油站不参与活动
                    return result;
                }
                //获得油品的立减规则
                ReductionOilRelations oilRelationsQuery=new ReductionOilRelations();
                oilRelationsQuery.setActivityId(reductionActivity.getActivityId());
                oilRelationsQuery.setOilId(Long.parseLong(payOrder.getOilName()));
                List<ReductionOilRelations> oilRelations=reductionOilRelationsMapper.query(oilRelationsQuery);
                if(oilRelations.size()>0){
                    ReductionOilRelations reductionOilRelations = oilRelations.get(0);
                    ReductionRules rulesQuery=new ReductionRules();
                    rulesQuery.setActivityOilId(reductionOilRelations.getActivityOilId());
                    List<ReductionRules> rules = reductionRulesService.selectReductionRulesList(rulesQuery);
                    rules=rules.stream().sorted(Comparator.comparing(ReductionRules::getFull)).collect(Collectors.toList());
                    //判断按什么金额立减
                    BigDecimal rechargeAmt = activityBalanceRecord.getRechargeAmt();
                    BigDecimal yhBalance = activityBalanceRecord.getBalance();
                    ReductionRules matchRule=null;
                    for (ReductionRules rule : rules) {
                        if(rechargeAmt.doubleValue()>=rule.getFull()){
                            matchRule=rule;
                        }
                    }
                    if(yhBalance.compareTo(BigDecimal.ZERO)<=0){
                        //如果优惠余额小于需支付的金额
                        return result;
                    }
                    ReductionRules fRules = rules.get(0);
                    fRules.setActivityType(reductionActivity.getActivityType());
                    fRules.setActivityMode(reductionActivity.getActivityMode());
                    reductionActivity.setFRules(fRules);
                    if(matchRule!=null){
                        //如果满足立减的要求
                        boolean check = checkReductionActivity(reductionActivity, payOrder, appUserInfos);
                        if(check){
                            BigDecimal rchReductionAmt = getRCHReductionAmt(reductionActivity, matchRule, payOrder);
                            List<CouponUser> couponList2;
                            if (StringUtils.equals("2",payOrderRequest.getCardFlag()) && Objects.equals(stationInfo.getCouponDzkExclusiveFlag(),0)) {
                                // 电子卡支付，且油站电子卡优惠劵互斥开关开启
                                couponList2 = Collections.emptyList();
                            }else{
                                couponList2 = getCouponList(stationInfo, appUserInfos, payOrder.getOilName(), stationInfo.getStationId(), payOrderRequest.getPayType(), payOrder.getAmt(), rchReductionAmt, reductionActivity, payOrderRequest.getNewCreatefalg());
                            }
                            result.put("rCHReductionAmt",rchReductionAmt);
                            result.put("couponList",couponList2);
                            result.put("activityRule",reductionActivity.getActivityRule());
                            result.put("rule",reductionActivity.getFRules());
                            result.put("reductionActivity",reductionActivity);

                            ReductionActivityLog reductionActivityLog = new ReductionActivityLog();
                            reductionActivityLog.setCreateTime(new Date());
                            reductionActivityLog.setCreateUser(Long.valueOf(appUserInfos.getUserId()));
                            reductionActivityLog.setCutAmount(rchReductionAmt.doubleValue());
                            reductionActivityLog.setOrderId(Long.valueOf(payOrder.getOrderId()));
                            reductionActivityLog.setReductionActivityId(reductionActivity.getActivityId());
                            reductionActivityLog.setUserId(Long.valueOf(appUserInfos.getUserId()));
                            reductionActivityLogMapper.insertReductionActivityLog(reductionActivityLog);
                            return result;
                        }
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> getRCHReductionAmt(String physicalCardNo, BigDecimal amt,Long stationId,Long oilId,String orderLiters) {
        PhysicalCard physicalCard = physicalCardMapper.selectByPhysicalCardNo(physicalCardNo);
        String userGrade = "0";
        Map<String,Object> result=new HashedMap();
        BigDecimal rCHReductionAmt=BigDecimal.ZERO;
        result.put("rCHReductionAmt",rCHReductionAmt);

        ReductionActivityBalanceRecord recordQuery=new ReductionActivityBalanceRecord();
        //判断是汽油还是柴油
        //recordQuery.setUserId(userId.longValue());
        recordQuery.setPhysicalCardNo(physicalCardNo);
        Station station = stationMapper.selectStationById(stationId.intValue());
        List<ReductionActivityBalanceRecord> records=reductionActivityBalanceRecordService.query(recordQuery);
        if(records.size()>0){
            //有优惠余额
            ReductionActivityBalanceRecord activityBalanceRecord = records.get(0);
            //查询立减规则  activityUse：RCH  station enterpriseId
            ReductionActivity activityQuery = new ReductionActivity();
            activityQuery.setActivityUse(ReductionActivityBalanceRecord.activityType_RCH);
            activityQuery.setEnterpriseId(station.getEnterpriseId().longValue());
            activityQuery.setMemberCategory(activityBalanceRecord.getNewUserFlag());
            activityQuery.setStationId(stationId);
            activityQuery.setOilId(oilId);
            activityQuery.setPhysicalCardType(physicalCard.getCardType());
            //activityQuery.setMemberLevel(userGrade);
            //activityQuery.setSuperUser(appUserInfos.getSuperUser());
            List<ReductionActivity> reductionActivities = reductionActivityMapper.selectReductionActivityList(activityQuery);
            reductionActivities = reductionActivities.stream().filter(r->checkEffectiveTime(r)).collect(Collectors.toList());
            //reductionActivities=checkLabelUser(reductionActivities,appUserInfos.getMobilePhone());
            if(reductionActivities.size()>0){
                //取最新的一个
                ReductionActivity reductionActivity = reductionActivities.get(0);
                //判断该油站是否有立减活动
                ReductionStationRelations stationRelationsQuery=new ReductionStationRelations();
                stationRelationsQuery.setActivityId(reductionActivity.getActivityId());
                stationRelationsQuery.setStationId(stationId);
                List<ReductionStationRelations> reductionStationRelations = reductionStationRelationsMapper.selectReductionStationRelationsList(stationRelationsQuery);
                if(reductionStationRelations.size()==0){
                    //该油站不参与活动
                    return result;
                }
                //获得油品的立减规则
                ReductionOilRelations oilRelationsQuery=new ReductionOilRelations();
                oilRelationsQuery.setActivityId(reductionActivity.getActivityId());
                oilRelationsQuery.setOilId(oilId);
                List<ReductionOilRelations> oilRelations=reductionOilRelationsMapper.query(oilRelationsQuery);
                if(oilRelations.size()>0){
                    ReductionOilRelations reductionOilRelations = oilRelations.get(0);
                    ReductionRules rulesQuery=new ReductionRules();
                    rulesQuery.setActivityOilId(reductionOilRelations.getActivityOilId());
                    List<ReductionRules> rules = reductionRulesService.selectReductionRulesList(rulesQuery);
                    rules=rules.stream().sorted(Comparator.comparing(ReductionRules::getFull)).collect(Collectors.toList());
                    //判断按什么金额立减
                    BigDecimal rechargeAmt = activityBalanceRecord.getRechargeAmt();
                    BigDecimal yhBalance = activityBalanceRecord.getBalance();
                    ReductionRules matchRule=null;
                    for (ReductionRules rule : rules) {
                        if(rechargeAmt.doubleValue()>=rule.getFull()){
                            matchRule=rule;
                        }
                    }
                    if(yhBalance.compareTo(BigDecimal.ZERO)<=0){
                        //如果优惠余额小于需支付的金额
                        return result;
                    }

                    reductionActivity.setFRules(matchRule);
                    if(matchRule!=null){
                        //如果满足立减的要求
                        boolean check = /*checkReductionActivity(reductionActivity, payOrder, appUserInfos)*/true;
                        if(check){
                            PayOrder payOrder=new PayOrder();
                            payOrder.setOrderLiters(orderLiters);
                            payOrder.setAmt(amt.doubleValue());
                            BigDecimal rchReductionAmt = getRCHReductionAmt(reductionActivity, matchRule, payOrder);
                            result.put("rCHReductionAmt",rchReductionAmt);
                            result.put("activityRule",reductionActivity.getActivityRule());
                            result.put("rule",reductionActivity.getFRules());
                            result.put("reductionActivity",reductionActivity);
                            return result;
                        }
                    }
                }
            }
        }
        return result;
    }

    public boolean checkEffectiveTime(ReductionActivity reductionActivitie){
        return reductionActivitie.getStartDate().before(new Date());
    }
    @Override
    public List<ReductionActivity> checkLabelUser(List<ReductionActivity> reductionActivities,String mobilePhone,Long enterpriseId){
        List<ReductionActivity> result=new ArrayList<>();
        List<ReductionActivity> labelActivities=new ArrayList<>();
        for (ReductionActivity reductionActivity : reductionActivities) {
            if(StringUtils.isNotEmpty(reductionActivity.getMemberTags())){
                if(StringUtils.contains(reductionActivity.getMemberTags(),"labelUser")){
                    //如果活动设置了标签用户，判断该用户在不在该活动的标签用户内
                    CustomerLabel customerLabel=new CustomerLabel();
                    customerLabel.setActivityId(reductionActivity.getActivityId());
                    customerLabel.setPhone(mobilePhone);
                    customerLabel.setDelFlag("0");
                    List<CustomerLabel> customerLabels=labelMapper.getCustomerLabelList(customerLabel);
                    customerLabels=customerLabels.stream().filter(c->c.getStartDate().before(new Date())&&c.getEndDate().after(new Date())).collect(Collectors.toList());
                    if(customerLabels.size()>0){
                        result.add(reductionActivity);
                        labelActivities.add(reductionActivity);
                    }
                }
            }else{
                //不需要判断该用户是不是这个活动的标签用户
                result.add(reductionActivity);
            }
        }
        //判断用户是不是标签用户
        if(StringUtils.isNotEmpty(mobilePhone)){
            CustomerLabel cl=new CustomerLabel();
            cl.setPhone(mobilePhone);
            cl.setDelFlag("0");
            cl.setEnterpriseId(enterpriseId.intValue());
            if(labelMapper.getCustomerLabelList(cl).size()>0){
                return labelActivities;
            }
        }

        return result;
    }
    @Override
    public List<ReductionActivitiesAmountVO> checkLabelUser2(List<ReductionActivitiesAmountVO> reductionActivities,String mobilePhone){
        List<ReductionActivitiesAmountVO> result=new ArrayList<>();
        List<ReductionActivitiesAmountVO> labelActivities=new ArrayList<>();
        for (ReductionActivitiesAmountVO reductionActivity : reductionActivities) {
            if(StringUtils.isNotEmpty(reductionActivity.getMemberTags())){
                if(StringUtils.contains(reductionActivity.getMemberTags(),"labelUser")){
                    if(StringUtils.isNotEmpty(mobilePhone)){
                        //如果活动设置了标签用户，判断该用户在不在该活动的标签用户内
                        CustomerLabel customerLabel=new CustomerLabel();
                        customerLabel.setActivityId(reductionActivity.getActivityId().longValue());
                        customerLabel.setPhone(mobilePhone);
                        customerLabel.setDelFlag("0");
                        List<CustomerLabel> customerLabels=labelMapper.getCustomerLabelList(customerLabel);
                        customerLabels=customerLabels.stream().filter(c->c.getStartDate().before(new Date())&&c.getEndDate().after(new Date())).collect(Collectors.toList());
                        if(customerLabels.size()>0){
                            result.add(reductionActivity);
                            labelActivities.add(reductionActivity);
                        }
                    }
                }
            }else{
                //不需要判断该用户是不是这个活动的标签用户
                result.add(reductionActivity);
            }
        }
        //判断用户是不是标签用户
        if(StringUtils.isNotEmpty(mobilePhone)){
            CustomerLabel cl=new CustomerLabel();
            cl.setPhone(mobilePhone);
            cl.setDelFlag("0");
            if(labelMapper.getCustomerLabelList(cl).size()>0){
                return labelActivities;
            }
        }

        return result;
    }
    public boolean checkReductionActivity(ReductionActivity reductionActivity,PayOrder payOrder,AppUserInfo appUserInfos){
        SimpleDateFormat simFmt = new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> queryMap = new HashMap<String,Object>();
        queryMap.put("userId",appUserInfos.getUserId());
        queryMap.put("reductionActivityId",reductionActivity.getActivityId());
        queryMap.put("startDate",simFmt.format(new Date())+" 00:00:00");
        queryMap.put("endDate",simFmt.format(new Date())+" 23:59:59");
        Map<String, Object> countMap = reductionActivityMapper.selectActivityCount(queryMap);
        if(reductionActivity.getMaxCount() != 0){
            Integer maxCount = Integer.valueOf(reductionActivity.getMaxCount().toString());
            if(Integer.valueOf(countMap.get("allCount").toString()) >= maxCount){
                //超出单次活动最大参与次数限制
                return false;
            }
        }
        /*if(reductionActivity.getAntiCheating().equals("0")){
            Integer countOfDay = Integer.valueOf(reductionActivity.getCountOfDay().toString());
            //开启了每日次数限制
            if(Integer.valueOf(countMap.get("dayCount") .toString())>= countOfDay){
                //超出单日活动最大参与次数限制
                return false;
            }
        }else{
            if(Integer.valueOf(countMap.get("dayCount") .toString())>= 1){
                //超出单日活动最大参与次数限制
                return false;
            }
        }
        if(isAmtUpperLimit(reductionActivity,BigDecimal.valueOf(payOrder.getAmt()))){
            //超过金额上限
            return false;
        }*/
        return true;
    }

    public boolean isAmtUpperLimit(ReductionActivity reductionActivity,BigDecimal amt){
        BigDecimal amtUpperLimit = reductionActivity.getAmtUpperLimit();
        if(amtUpperLimit!=null){
            if(amtUpperLimit.compareTo(amt)==-1){
                //amtUpperLimit<amt
                return true;
            }
        }
        return false;
    }

    public BigDecimal getRCHReductionAmt(ReductionActivity reductionActivity,ReductionRules matchRule,PayOrder payOrder){
                        /* activityUse 活动用途：CSP消费、RCH充值、LABEl标签
                        activityType 活动类型：RFA-按固定金额 LOR-按固定数量 AAL-每升立减
                        activityMode 活动方式：FAD-定额立减 PAR-百分比立减 RDD-随机立减*/
        String activityType = reductionActivity.getActivityType();
        String activityMode = reductionActivity.getActivityMode();
        Double cut = matchRule.getCut();
        BigDecimal reductionAmt=BigDecimal.ZERO;
        if(activityType.equals("RFA")){
               //暂不支持
        }else if(activityType.equals("LOR")){
            //暂不支持
        }else if(activityType.equals("AAL")){
            //每升立减
            if(activityMode.equals("FAD")){
                //FAD-定额立减
                reductionAmt = BigDecimal.valueOf(matchRule.getCut()).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2, RoundingMode.HALF_UP);
            }else if(activityMode.equals("PAR")){
                //PAR-百分比立减
                reductionAmt = BigDecimal.valueOf(payOrder.getAmt()).multiply(BigDecimal.valueOf(matchRule.getCut())).multiply(new BigDecimal("0.01")).setScale(2,RoundingMode.HALF_UP);
            }else if(activityMode.equals("RDD")){
                //RDD-随机立减
                Double cutMax = matchRule.getCutMax();
                Double cutMin = matchRule.getCutMin();
                double random = Math.random() * (cutMax - cutMin) + cutMin;
                reductionAmt = new BigDecimal(random).setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(payOrder.getOrderLiters())).setScale(2, BigDecimal.ROUND_HALF_UP);

            }

        }
        return reductionAmt;
    }


    /**
     * 根据当天是周几和几号获取活动列表，queryMap需要包含day和week参数
     * 因为数据库改动，该方法兼容获取旧活动
     * @param queryMap
     * @return
     */
    private List<ReductionActivity> queryOldActivityByDayAndWeek(Map<String,Object> queryMap){
        //根据周和月查询的所有活动，查询逻辑是新的，可能会包含旧的，也可能不包含
        List<ReductionActivity> newList = reductionActivityMapper.selectByOrderInfo(queryMap);
        //根据周和月查询的所有旧活动，newList、oldList都是根据activityId排序
        queryMap.put("createTime",OLD_ACTIVITY_CREATE_TIME_STR);
        List<ReductionActivity> oldList = reductionActivityMapper.selectByOrderInfoOld(queryMap);
        queryMap.remove("createTime");

        int newIndex = 0;
        int oldIndex = 0;
        while (((newIndex < newList.size()) && (oldIndex < oldList.size()))) {
            Long newId = newList.get(newIndex).getActivityId();
            Long oldId = oldList.get(oldIndex).getActivityId();
            if(Objects.equals(newId, oldId)){
               newList.remove(newIndex);
               oldIndex++;
            }else if(newId > oldId){
                oldIndex++;
            }else{
                newIndex++;
            }
        }
        newList.addAll(oldList);
        return newList;
    }

    @Override
    public ReductionAndCouponDTO calculateReductionDiscount(AddPayOrderParam orderParam, PayOrder payOrder, Station station, StaOilGun staOilGun, AppUserInfo userInfo) {
        BigDecimal discountAmt;
        if (userInfo == null) {
            // 没有用户信息
            ReductionActivitiesVO activitiesVO=new ReductionActivitiesVO();
            activitiesVO.setActivityUse("CSP");
            activitiesVO.setAmt(new BigDecimal(orderParam.getAmt()));
            String nowStr = LocalDateTimeUtil.parse(LocalDateTime.now());
            activitiesVO.setDateTime(nowStr);
            activitiesVO.setEnterpriseId(orderParam.getEnterpriseId());
            activitiesVO.setOilId(staOilGun.getOilId());
            activitiesVO.setOrderLiters(orderParam.getOrderLiters());
            activitiesVO.setStationId(orderParam.getStationId());
            activitiesVO.setPaymentMethod(orderParam.getPayType());
            discountAmt=payOrderService.reductionActivitiesAmountCalculation(activitiesVO,null).setScale(2, BigDecimal.ROUND_HALF_UP);
            if(activitiesVO.getActivityId()!=null) {
                //更新活动的预算，避免多个用户同时支付时，产生超预算的问题
                this.updateReductionActivityBudget(discountAmt.negate(), activitiesVO.getActivityId()==null?-1:activitiesVO.getActivityId());
            }
            if (activitiesVO.getActivityId() != null) {
                ReductionAndCouponDTO dto = ReductionAndCouponDTO.newEmptyInstance();
                dto.setReductionAmt(discountAmt);
                dto.setActivityId(Long.valueOf(activitiesVO.getActivityId()));
                return dto;
            }
        }else{
            // 有用户信息
            //计算优惠金额
            PayOrderRequest request = new PayOrderRequest();
            request.setCardFlag("1"); //设置电子标识，不使用电子卡
            request.setOilId(staOilGun.getOilId()); // 设置oilId
            request.setPayType(payOrder.getPayType());
            request.setReceivableAmt(String.valueOf(orderParam.getReceivableAmt()));
            request.setStationId(station.getStationId());
            payOrder.setOilId(staOilGun.getOil().getOilId());
            Map<String,Object> amountMap = this.selectReductionByPayOrderCoupon(userInfo, payOrder, "CSP", request, station,staOilGun);
            if(amountMap != null && amountMap.containsKey("activityId") && amountMap.get("activityId") != null){
                ReductionAndCouponDTO dto = ReductionAndCouponDTO.newEmptyInstance();
                dto.setReductionAmt((BigDecimal) amountMap.get("reductionAmount"));
                dto.setActivityId((Long) amountMap.get("activityId"));
                return dto;
            }
        }
        return null;
    }
}
